一.Laravel 的装置与配置
1. 下载 Composer-Setup.exe (getcomposer.org)并装置
2. 挪动到 xampp/hotdocs 文件夹,执行以下命令
php composer create-project –prefer-dist laravel/laravel blog
3. 用 PhpStorm 关上能够看到如图我的项目构造
4. 能够间接输出命令 php artisan serve 运行,也能够拜访 apache, 显示如下图示意胜利
这时 Laravel 就装置胜利了。
5. 批改.env 文件中的数据库信息
二. 编写 api 接口
1. 新建数据库建表插入数据
DROP TABLE IF EXISTS `book`;
CREATE TABLE `book` (`id` int(11) NOT NULL AUTO_INCREMENT,
`book_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
`book_sort` int(11) DEFAULT NULL,
`book_mark` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = MyISAM AUTO_INCREMENT = 5 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of book
-- ----------------------------
INSERT INTO `book` VALUES (1, '水浒传', 1, '四大名著');
INSERT INTO `book` VALUES (2, '西游记', 1, '孙悟空');
INSERT INTO `book` VALUES (3, '红楼梦', 2, '无');
INSERT INTO `book` VALUES (4, '三国演义', 2, '');
3. 新建 Model 和 Controller
php artisan make:model Models/Book
php artisan make:controller BookController
批改 Book.php
<?php
namespace AppModelsModels;
use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateDatabaseEloquentModel;
class Book extends Model
{
use HasFactory;
/** 关联到模型的数据表
* @var string
*/ protected $table = 'book';
/**Laravel 有默认工夫字段,不须要能够批改成 false
* @var bool
*/ public $timestamps = false;
}
4. 创立简略的 api
编写 BookController.php
<?php
namespace AppHttpControllers;
use AppModelsModelsBook;
use IlluminateHttpRequest;
class BookController extends Controller
{public function getBookById($id)
{ // 依据 id 查问
$book = Book::find($id);
// return response()是返回想要 json()转换成 json 字符串然而是 unicode setEncodingOptions 设置编码
return response()->json($book)->setEncodingOptions(JSON_UNESCAPED_UNICODE);
}
}
编写 routes/api.php
<?php
use IlluminateHttpRequest;
use IlluminateSupportFacadesRoute;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::middleware('auth:api')->get('/user', function (Request $request) {return $request->user();
});
Route::any('/book/{id}',[AppHttpControllersBookController::class,'getBookById']);
5.php artisan serve 或者间接拜访 apache
一个简略接口的编写到此结束,这样写起来很简略,然而两头也遇到了点小问题,比方 MySQL 编码问题,Navcat 有很大的问题,show variables like ‘char%’; 在 MySQL cmd 中显示是 utf- 8 然而在 navcat 中却成了 latin, 这个要在 navcat 连贯那里编辑编码为主动, 这样就能够和零碎的一样了。