一、注册用户
进入 tinker
php artisan tinker
注册用户
$user = new App\User;
$user->name = 'lulubin';
$user->email = 'alulubin@gmail.com';
$user->password = bcrypt('123456');
$user->save();
二、创建课程
修改控制器:app/Http/Controllers/LessonsController.php,添加中间件
public function __construct()
{
$this->middleware('auth.basic',['only'=>'store','update']);
}
注释 app/Http/Kernel.php
\App\Http\Middleware\VerifyCsrfToken::class
使用 postman:https://lulublog.cn/p/kuExT1
请求方式:POST
地址栏:http://localhost:8000/api/v1/lessons
点击 Send,出现状态 401Unauthorized
修改 app/Lesson.php
protected $fillable = ['title', 'content', 'free'];
修改控制器:app/Http/Controllers/LessonsController.php
use Validator;
public function store(Request $request)
{
$rules = [
'title' => 'required',
'content' => 'required',
'free' => 'required',
];
$messages = [
'title.required' => '标题不能为空',
'content.required' => '内容不能为空',
'free.required' => '是否免费不能为空',
];
$validator = Validator::make($request->all(), $rules, $messages);
if ($validator->fails()) {
return response()->json([
'status' => 'error',
'message' => $validator->errors()->first()
])->setStatusCode(422);
}
Lesson::create($request->all());
return response()->json([
'status' => 'success',
'message' => 'lesson created'
])->setStatusCode(201);
}
打开 postman,将 127.0.0.1 替换成 localhost