从零开始学Laravel(一)Laravel安装配置编写简单api接口

一.Laravel的安装与配置

1.下载Composer-Setup.exe (getcomposer.org)并安装
2.移动到xampp/hotdocs文件夹,执行以下命令

php composer create-project --prefer-dist laravel/laravel blog

3.用PhpStorm打开可以看到如图项目结构
从零开始学Laravel(一)Laravel安装配置编写简单api接口_第1张图片

二.编写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

4.创建简单的api
编写BookController.php

json($book)->setEncodingOptions(JSON_UNESCAPED_UNICODE);
 }
}

编写 routes/api.php

get('/user', function (Request $request) {
 return $request->user();
});
Route::any('/book/{id}',[AppHttpControllersBookController::class,'getBookById']);

5.php artisan serve或者直接访问apache
从零开始学Laravel(一)Laravel安装配置编写简单api接口_第2张图片
一个简单接口的编写到此结束,这样写起来很简单,但是中间也遇到了点小问题,比如MySQL编码问题,Navcat有很大的问题,show variables like 'char%';在MySQL cmd中显示是utf-8但是在navcat中却成了latin,这个要在navcat连接那里编辑编码为自动,这样就可以和系统的一样了。

你可能感兴趣的:(php,laravel)