Laravel6 簡單使用 API 註冊訪問實現(適合菜鳥)

aidybnt發表於2019-10-22

本篇文章只適合剛入門的菜鳥檢視。大神熟練工請忽略。

本人是一名對程式設計愛好者,從2004年就開始搗鼓程式這塊。
不是靠這個吃飯。學習這個一方面有興趣,另一方對工作生活有很多幫助。
從最早的VB,簡單HTML,到後來的Flash ActionScript,在到後來java、C#都有過簡單的瞭解和學習。
後來就感受到PHP的魅力,在後來HTML5和CSS3學的最好。
在後來了解了MVC思想,然後就用了TP,從3到5都用過。坑的真很多。。。過程很痛苦。
微信公眾號火的那一陣,開發過微信服務號的應用,還賺點小錢。挺有成就感的。
最近自己在工作上有一個需求,比較灰色的需求,只能自己搞。
但是我真的不想用TP,至於什麼原因你們懂的,我只能說國產的氛圍很糟糕。
然後選來選去,確定了用laravel,直接從6搞起。反正我的程式,使用的圈子也不大。
經過幾天搗鼓,我才發現。。。這玩意真特麼好啊,果然名氣大不是蓋的。
然後就是搗鼓,首先順利搞了傳統的web方式實現,很輕鬆就搞定了。目前程式正在順利使用中。
但是我不甘心啊,我想搞明白當下最流行的MVVC。
然後就去搗鼓什麼Node,Webpack,但是我發現,我應該首先從伺服器做好API介面才對,至於前端這塊,對於我這樣 簡單的應用來講,問題不大。
我就不停的找資料啊,看啊。。。
哎。。。受不了,絕大部分資料都不是laravel6之前的,好多東西又都對不上。
沒辦法,只能找一個差不多的,然後自己不停的去嘗試。
現在把簡單的API介面實現記錄如下。

admins表

<?php

namespace App\Model;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Str;

/**
 * @property string api_token
 */
class Admin extends Model
{
    use SoftDeletes;

    //指定表明
    //protected $table = 'admins';

    //指定主鍵名
    //protected $primaryKey = 'id';

    //維護預設的時間戳
    public $timestamps = true;

    //黑白名單 僅在新增create方法時有效
    //protected $fillable = ['name', 'type'];
    protected $guarded = [];

    //在生成及儲存token
    public function generateToken()
    {
        $this->api_token = Str::random(60);
        $this->save();
        return $this->api_token;
    }

}

hfs表

<?php

namespace App\Model;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Hf extends Model
{
    use SoftDeletes;

    //protected $dates = ['deleted_at'];

    //指定表明
    //protected $table = 'show';

    //指定主鍵名
    protected $primaryKey = 'id';

    //維護預設的時間戳
    public $timestamps = true;

    //黑白名單 僅在新增create方法時有效
    //protected $fillable = ['name', 'type'];
    protected $guarded = [];

}

以上資料對應 Admin.php Hf.php 兩個模型

Admin.php

<?php

namespace App\Model;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Str;

/**
 * @property string api_token
 */
class Admin extends Model
{
    use SoftDeletes;

    //指定表明
    //protected $table = 'admins';

    //指定主鍵名
    //protected $primaryKey = 'id';

    //維護預設的時間戳
    public $timestamps = true;

    //黑白名單 僅在新增create方法時有效
    //protected $fillable = ['name', 'type'];
    protected $guarded = [];

    //在生成及儲存token
    public function generateToken()
    {
        $this->api_token = Str::random(60);
        $this->save();
        return $this->api_token;
    }

}

Hf.php

<?php

namespace App\Model;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Hf extends Model
{
    use SoftDeletes;

    //protected $dates = ['deleted_at'];

    //指定表明
    //protected $table = 'show';

    //指定主鍵名
    protected $primaryKey = 'id';

    //維護預設的時間戳
    public $timestamps = true;

    //黑白名單 僅在新增create方法時有效
    //protected $fillable = ['name', 'type'];
    protected $guarded = [];

}

Admin控制器

<?php

namespace App\Http\Controllers\Api;

use App\Model\Admin;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Resources\Admin as AdminResources;
use DB;

class AdminController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * [[@return](https://learnku.com/users/31554)](https://learnku.com/users/31554) \Illuminate\Http\Response
     */
    public function index()
    {
        return new AdminResources(Admin::query()->find(1));
    }

    /**
     * Show the form for creating a new resource.
     *
     * [[@return](https://learnku.com/users/31554)](https://learnku.com/users/31554) \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param \Illuminate\Http\Request $request
     * [[@return](https://learnku.com/users/31554)](https://learnku.com/users/31554) \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param int $id
     * [[@return](https://learnku.com/users/31554)](https://learnku.com/users/31554) \Illuminate\Http\Response
     */
    public function show($id)
    {
        $res = DB::table('admins')->where('id', $id)->first();
        if ($res === null) { //檢查傳過來的ID是否能查詢出資料
            //throw new ApiException('非法操作');
            return response(['message' => '非法操作'], 422);
        } else {
            return new AdminResources(Admin::query()->find($id));
        }
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param int $id
     * [[@return](https://learnku.com/users/31554)](https://learnku.com/users/31554) \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param \Illuminate\Http\Request $request
     * @param int $id
     * [[@return](https://learnku.com/users/31554)](https://learnku.com/users/31554) \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param int $id
     * [[@return](https://learnku.com/users/31554)](https://learnku.com/users/31554) \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}

HfController

<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Model\Hf;
use Illuminate\Http\Request;
use App\Http\Resources\Hf as HfResource;
use DB;

class HfController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * [[@return](https://learnku.com/users/31554)](https://learnku.com/users/31554) \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     *
     * [[@return](https://learnku.com/users/31554)](https://learnku.com/users/31554) \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param \Illuminate\Http\Request $request
     * [[@return](https://learnku.com/users/31554)](https://learnku.com/users/31554) \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param int $id
     * [[@return](https://learnku.com/users/31554)](https://learnku.com/users/31554) \Illuminate\Http\Response
     */
    public function show($id)
    {
        $res = DB::table('hfs')->where('id', $id)->first();
        if ($res === null) {
            //throw new ApiException('非法操作');
            return response(['message' => '非法操作'], 422);
        } else {
            return new HfResource(Hf::query()->find($id));
        }
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param int $id
     * [[@return](https://learnku.com/users/31554)](https://learnku.com/users/31554) \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param \Illuminate\Http\Request $request
     * @param int $id
     * [[@return](https://learnku.com/users/31554)](https://learnku.com/users/31554) \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param int $id
     * [[@return](https://learnku.com/users/31554)](https://learnku.com/users/31554) \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}

用來檢測是否ajax訪問和是否攜帶token請求,別忘了註冊中介軟體

<?php

namespace App\Http\Middleware;

use Closure;

class CheckAjax
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * [[@return](https://learnku.com/users/31554)](https://learnku.com/users/31554) mixed
     */
    public function handle($request, Closure $next)
    {
        if (!$request->ajax()) { //檢測是否ajax訪問
            return response(['message' => '非法訪問']);
        }
        return $next($request);
    }
}
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;

class CheckToken
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * [[@return](https://learnku.com/users/31554)](https://learnku.com/users/31554) mixed
     */
    public function handle($request, Closure $next)
    {
        if (Auth::guard('api')->guest()) { //檢測是否攜帶token請求
            return response([
                'message' => '沒有訪問許可權'
            ]);
        }
        return $next($request);
    }
}

註冊路由中介軟體,順序我放在上面

protected $routeMiddleware = [
        'checkAjax' => \App\Http\Middleware\CheckAjax::class,
        'checkToken' => \App\Http\Middleware\CheckToken::class,
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
        'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
    ];

Admin.php

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

/**
 * @property mixed id
 * @property mixed api_token
 * @property mixed name
 * @property mixed email
 * @property mixed created_at
 * @property mixed updated_at
 */
class Admin extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param \Illuminate\Http\Request $request
     * [[@return](https://learnku.com/users/31554)](https://learnku.com/users/31554) array
     */
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'api_token' => $this->api_token,
            'name' => $this->name,
            'email' => $this->email,
            'created_at' => $this->created_at,
            'updated_at' => $this->updated_at,
        ];
    }
}

Hf.php

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

/**
 * @property mixed returnNo
 * @property mixed verCode;
 * @property mixed account;
 * @property mixed cardNo;
 * @property mixed bank;
 * @property mixed type;
 * @property mixed lowMoney;
 * @property mixed upMoney;
 * @property mixed transDate;
 * @property mixed serialNo;
 * @property mixed description;
 * @property mixed printDate;
 * @property mixed sort;
 * @property mixed project;
 * @property mixed lot;
 * @property mixed pTime;
 * @property mixed created_at;
 * @property mixed updated_at;
 */
class Hf extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param \Illuminate\Http\Request $request
     * [[@return](https://learnku.com/users/31554)](https://learnku.com/users/31554) array
     */
    public function toArray($request)
    {
        return ['returnNo' => $this->returnNo,
            'verCode' => $this->verCode,
            'account' => $this->account,
            'cardNo' => $this->cardNo,
            'bank' => $this->bank,
            'type' => $this->type,
            'lowMoney' => $this->lowMoney,
            'upMoney' => $this->upMoney,
            'transDate' => $this->transDate,
            'serialNo' => $this->serialNo,
            'description' => $this->description,
            'printDate' => $this->printDate,
            'sort' => $this->sort,
            'project' => $this->project,
            'lot' => $this->lot,
            'pTime' => $this->pTime,
            'created_at' => $this->created_at,
            'updated_at' => $this->updated_at,
        ];
//        return parent::toArray($request);
    }
}
<?php

return [

    'defaults' => [
        'guard' => 'web',
        'passwords' => 'users',
    ],

    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

        'api' => [
            'driver' => 'token',
            'provider' => 'admins',
            'hash' => false,
        ],
    ],

    'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\User::class,
        ],
        'admins' => [
            'driver' => 'eloquent',
            'model' => App\Model\Admin::class,
        ],

        // 'users' => [
        //     'driver' => 'database',
        //     'table' => 'users',
        // ],
    ],

    'passwords' => [
        'users' => [
            'provider' => 'users',
            'table' => 'password_resets',
            'expire' => 60,
        ],
    ],

    'password_timeout' => 10800,

];
<?php

namespace App\Exceptions;

class ApiException extends Exception
{
    public function __construct($message = "")
    {
        parent::__construct($message);
    }
}
<?php

namespace App\Exceptions;

use Exception;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that are not reported.
     *
     * @var array
     */
    protected $dontReport = [
        //
    ];

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array
     */
    protected $dontFlash = [
        'password',
        'password_confirmation',
    ];

    /**
     * Report or log an exception.
     *
     * @param \Exception $exception
     * [[@return](https://learnku.com/users/31554)](https://learnku.com/users/31554) void
     */
    public function report(Exception $exception)
    {
        parent::report($exception);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Exception $exception
     * [[@return](https://learnku.com/users/31554)](https://learnku.com/users/31554) \Illuminate\Http\Response
     */
    public function render($request, Exception $exception)
    {
        if ($exception instanceof ApiException) {
            $result = [
                "data" => $exception->getMessage(),
            ];
            return response($result, 422);
        }

        return parent::render($request, $exception);
    }
}
<?php

use Illuminate\Http\Request;

Route::middleware('checkAjax')->group(function () { //檢測是否為ajax訪問

    Route::post('register', 'Auth\RegisterController@register'); //註冊

    Route::namespace('Api')->group(function () { //規範
        // 在 「App\Http\Controllers\Api」 名稱空間下的控制器
        Route::prefix('admin')->group(function () { //admin空間
            Route::get('/', 'AdminController@index');
            Route::get('show/{id}', 'AdminController@show');
        });

        Route::middleware('checkToken')->group(function () { //資料訪問必須要有token
            Route::prefix('hf')->group(function () { //恆豐銀行資料
                Route::get('show/{id}', 'HfController@show');
            });
        });
    });
});

準備工作齊活

Laravel6 簡單使用 API 註冊訪問實現(適合菜鳥)

Laravel6 簡單使用 API 註冊訪問實現(適合菜鳥)

Laravel6 簡單使用 API 註冊訪問實現(適合菜鳥)

Laravel6 簡單使用 API 註冊訪問實現(適合菜鳥)

Laravel6 簡單使用 API 註冊訪問實現(適合菜鳥)

Laravel6 簡單使用 API 註冊訪問實現(適合菜鳥)

Laravel6 簡單使用 API 註冊訪問實現(適合菜鳥)

搞定

按照以上做就可以在laravel6跑起來

裡面肯定存在一些問題,畢竟偶不是專業的。

對於簡單的應用應該可以用了,下面就可以安心搞前端了。

希望能夠幫助到和我一樣的菜鳥便宜們。

相關文章