Laravel從零開發後臺API(二)

以前咱們已經準備好了基本的安裝過程 如今咱們去實現一下具體的業務部分php

用戶的登陸與註冊

對於用戶註冊 這對於一款應用來講再正常不過了 爲了接下來咱們的效果 咱們能夠去生成一個UserControllerlaravel

即在項目終端執行chrome

$ php artisan make:controller App\\Api\\Controllers\UserController

生成用戶以後咱們暫時先不去編輯字段 後面咱們須要用到時再加json

返回字段數據沿用以前建立的Lesson Model 這裏咱們先在routes/api.php加上咱們的基本路由api

Route::middleware('auth:api')->get('/user', function (Request $request) {
    return $request->user();
});

$api = app('Dingo\Api\Routing\Router');
$api->version('v1', function ($api) {
    $api->group(['namespace' => 'App\Api\Controllers'], function ($api) {
        $api->get('lessons', 'LessonsController@index');
        $api->get('lessons/{id}', 'LessonsController@show');
    });
});

咱們就去訪問這個http://host/api/lessons 先去完成控制器的相關方法app

public function index()
{
    $lessons =  Lesson::all();
    
    return response()->json($data);
}

這只是簡單的返回Lessons的所有字段信息 可是咱們能夠看到已經返回了全部的字段信息less

可是這個時候有個問題就是 咱們的字段返回時不多是所有返回的 咱們確定會對一些字段進行篩選 這就用到了咱們以前建立的Transformers這個文件下的了工具

話很少說 在App/Api/Transformers目錄下新建LessonTranformerpost

use App\Lesson;
use League\Fractal\TransformerAbstract;

class LessonTransformer extends TransformerAbstract
{
    public function transform(Lesson $lesson)
    {
        return [
            'title' => $lesson['title'],
            'content' => $lesson['body'],
            'is_free' => (boolean)$lesson['free']
        ];
    }
}

這樣咱們就實現了對字段數據的映射 再去LessonController去對以前的全部字段進行映射測試

public function index()
{
    $lessons =  Lesson::all();

    return $this->collection($lessons,new LessonTransformer());
}

固然這個要想實現這個collection咱們須要使用Dingo提供給咱們的Helpers trait

這樣一來的話咱們以前所繼承的基類能夠這樣寫

use Dingo\Api\Routing\Helpers;

class Controller extends BaseController
{
    use Helpers,AuthorizesRequests, DispatchesJobs, ValidatesRequests;

}

這樣咱們返回的就只有title content is_free這三個字段

一樣的若是咱們想要獲取其中一條數據的話 咱們也是能夠這樣去映射字段的

public function show($id)
{
    $lesson = Lesson::find($id);
    if(!$lesson){
        return $this->response()->errorNotFound("Lesson nt found");
    }
    return $this->response()->item($lesson,new LessonTransformer());
}

這裏我用的是Dingo提供給的返回方法 若是沒有這條數據會返回404和對應的錯誤信息

下面就是 結合jwt的auth認證
爲此咱們在App\Api\Controllers目錄下新建一個AuthController

這裏咱們須要去編寫咱們的認證方法和獲取認證用戶的方法

新建認證

public function authenticate(Request $request)
{
    // grab credentials from the request
    $credentials = $request->only('email','password');


    try {
        // attempt to verify the credentials and create a token for the user
        if (! $token = JWTAuth::attempt($credentials)) {
            return response()->json(['error' => 'invalid_credentials'], 401);
        }
    } catch (JWTException $e) {
        // something went wrong whilst attempting to encode the token
        return response()->json(['error' => 'could_not_create_token'], 500);
    }

    // all good so return the token
    return response()->json(compact('token'));
}

爲了執行這個方法 能夠去路由中定義

$api->version('v1', function ($api) {
    $api->group(['namespace' => 'App\Api\Controllers'], function ($api) {
        $api->post('user/login','AuthController@authenticate');
        $api->post('user/register','AuthController@register');
    });
});

這個時候再去查看一下咱們的路由的話就會看到新定義的post路由

爲了驗證請求的結果 咱們能夠使用postman這個chrome工具 去請求http://localhost:8000/api/use...

這個時候是會返回{"error":"invalid_credentials"}

爲了可以正確經過,咱們能夠在body部分給出用戶郵箱和密碼(用戶可用thinker建立一個) 這個時候就會正確返回一個token

固然爲了測試的話能夠直接去tinker新建一個用戶便可 這裏我已經新建了一個用戶郵箱是jellybean@163.com的用戶

圖片描述

這樣咱們就能夠拿到用戶的token 咱們在集成jwt認證時 添加了jwt:auth的中間件

這個其實很好理解 就好比一篇文章 若是用戶沒有登陸進來你是不能對文章進行收藏 評論等操做的

那麼這個token咱們是在用戶登陸以後或者用戶註冊以後會返回給客戶段一個token值 這樣用戶憑藉這個token

也就是一個證實你是已經登陸的用戶 你是咱們這個網站的用戶 這樣你就能夠發表文章等操做

這樣的話咱們能夠爲一些路由添加一些中間件

$api->group(['namespace' => 'App\Api\Controllers','middleware'=>'jwt.auth'],function ($api){
        $api->get('lessons','LessonsController@index');
        $api->get('lessons/{id}','LessonsController@show');
    });

這樣的話咱們再去訪問某一個lesson的話

圖片描述

提示咱們缺乏token 由於如今至關於一個沒有登陸的用戶去訪問這條路由 那麼咱們再去接上咱們的token的話

圖片描述

這下咱們就能夠訪問到對應的數據了 這個token也是會有過時時間的 若是過時了 咱們須要去更新這個token

在應用中咱們能夠加一個api_token字段來存儲這個字段 這樣每次用戶去訪問相應的路由的話咱們會去驗證這個token

固然 jwt 安裝成功後 ,默認使用的 auth 進行 認證 ,讀取的也是users表的數據

若是是須要驗證其餘的數據表的話能夠參照這篇文章 jwt 自定義 數據表 區別於 auth 中的 users 表

這樣基本就實現了一個基本的後臺接口的請求過程

參考個人博客文章

相關文章
相關標籤/搜索