Laravel Passport API 笔记

1、模型自行翻阅资料,官网入口: https://laravel-china.org/docs/laravel/5.5/passport/1309

2、routes/api.php 添加如下测试代码;

Route::group(['namespace' => 'API'], function (){
    Route::post('login', 'PassportController@login');
    Route::post('register', 'PassportController@register');

    Route::group(['middleware' => 'auth:api'], function (){
        Route::get('v1/passport', 'PassportController@passport');
    });
});

3、创建控制器,添加以下测试代码;

 request('email'), 'password' => request('password')]))
        {
            $user = Auth::user();
            // return response()->json($user);
            $this->content['token'] =  $user->createToken('MyApp')->accessToken;
            $status = 200;
        } else {

            $this->content['error'] = "未授权";
            $status = 401;
        }
        return response()->json($this->content, $status);
    }

    /**
     * Register api
     *
     * @return \Illuminate\Http\Response
     */
    public function register(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required',
            'email' => 'required|email',
            'password' => 'required',
            'c_password' => 'required|same:password',
        ]);

        if ($validator->fails()) {
            return response()->json(['error'=>$validator->errors()], 401);
        }

        $input = $request->all();
        $input['password'] = bcrypt($input['password']);
        $user = User::create($input);
        $success['token'] =  $user->createToken('MyApp')->accessToken;
        $success['name'] =  $user->name;

        return response()->json(['success'=>$success], $this->successStatus);
    }

    /**
     * details api
     *
     * @return \Illuminate\Http\Response
     */
    public function passport()
    {
        return response()->json(['user' => Auth::user()]);
    }

}

POSTMAN截图

Laravel Passport API 笔记_第1张图片

Laravel Passport API 笔记_第2张图片

欢迎交流

你可能感兴趣的:(laravel)