Laravel 5.4+ Dingo +JWT Rapid Build API System

Source: Internet
Author: User

刚进入新公司,比较忙,只能抽时间来写写比较简短的博文总结,还望见谅。 最近公司要从实业转型线上,决定用laravel 来做快速开发,而一些同事之前没有用过laravel,尤其是api 的快速搭建,一致想让我把搭建过程给分享出来,此为背景----也算是治疗懒癌的动机 ^_^ ~~~

Build process Record: We use laravel 5.4, because 5.6 seems to be more concise than this, when I use later to share
__
Create a Laravel Project

composer create-project --prefer-dist laravle/laravel myProject  ‘5.4.*‘

__
Install Dingo + JWT

"require":{        "dingo/api": "1.0.0-beta8",    "tymon/jwt-auth": "1.0.0-beta.3"},"minimum-stability":"dev",

Performing the installation

composer update

Configuration Items
config/app.php

"providers"=>[        ...        Dingo\Api\Provider\LaravelServiceProvider::class,        Tymon\JWTAuth\Providers\LaravelServiceProvider::class,],‘aliases‘ => [    ...    ‘JWTAuth‘ => Tymon\JWTAuth\Facades\JWTAuth::class]

config/api.php

‘auth‘ => [    ‘jwt‘ => Dingo\Api\Auth\Provider\JWT::class]

Publish configuration file: Terminal execution

php artisan vendor:publish --provider="Dingo\Api\Provider\LaravelServiceProvider"  //生成 api.phpphp artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"  //生成 jwt.php

Generate JWT key write. env

php artisan jwt:secret

In. Env, configure the Dingo at the end of the

API_STANDARDS_TREE=vnd // 环境API_SUBTYPE=myapp // 子类型API_PREFIX=api // 前缀API_DOMAIN=api.myapp.com //子域名  (前缀和子域名只能存在一个)可选API_VERSION=v1 // 版本API_NAME=My API // 名字(使用API Blueprint命令才会用到)API_CONDITIONAL_REQUEST=false // 带条件的请求API_STRICT=false // Strict模式API_DEFAULT_FORMAT=json // 响应格式API_DEBUG=true // 调试模式

The above configuration is not all necessary, can be selected according to the actual situation (above configuration, refer to network configuration), such as:

API_STANDARDS_TREE=vndAPI_SUBTYPE=emallAPI_PREFIX=apiAPI_VERSION=v1

__

Routing:
To create a new content in routers/api.php, two paths are registered and logged in:

//接管路由$api = app(‘Dingo\Api\Routing\Router‘);$api->version(‘v1‘, function ($api) {         $api->post(‘login‘, ‘App\Http\Controllers\Api\Auth\[email protected]‘);         $api->post(‘register‘, ‘App\Http\Controllers\Api\Auth\[email protected]‘);});

Generate Controller

php artisan make:controller Api/Auth/LoginControllerphp artisan make:controller Api/Auth/RegisterController  

__
Database configuration. env

DB_CONNECTION=mysqlDB_HOST=127.0.0.1DB_PORT=3306DB_DATABASE=51tbk.comDB_USERNAME=rootDB_PASSWORD=123

You can use data migration if you do not apply Laravel's own authentication system

php artisan make:model User -m   //生成user 模型的同时,创建数据迁移单独生成迁移文件php artisan make:migration create_users_table

Modify Content

public function up(){    Schema::create(‘users‘, function (Blueprint $table) {        $table->increments(‘id‘);        $table->string(‘name‘)->unique();        $table->string(‘email‘)->unique();        $table->string(‘password‘);        $table->rememberToken();        $table->timestamps();    });}

Generating tables

php artisan migrate

Edit model/users.php

<?phpnamespace App\Model;use Illuminate\Database\Eloquent\Model;use Illuminate\Foundation\Auth\User as Authenticatable;use Illuminate\Notifications\Notifiable;use Tymon\JWTAuth\Contracts\JWTSubject;use Illuminate\Foundation\Auth\User as Authenticatable;class Users extends Authenticatable implements JWTSubject {    use Notifiable;    protected $fillable = [‘name‘,‘email‘,‘password‘];    protected $hidden = [‘password‘,‘remember_token‘];    public function getJWTIdentifier(){        return $this->getKey();    }    public function getJWTCustomClaims(){        return [];    }}

__
Register registercontroller.php

<?phpnamespace app\http\controllers\api\auth;use app\http\controllers\controller;use App\User;use Dingo\Api\ Routing\helpers;use Illuminate\foundation\auth\registersusers;use Illuminate\http\request;use Illuminate\Support\    Facades\validator;use Tymon\jwtauth\facades\jwtauth;class Registercontroller extends Controller {use registersusers;    Use Helpers;        Public Function Register (Request $request) {$validator = $this->validator ($request->all ()); if ($validator->fails ()) {throw new Storeresourcefailedexception ("Validation Error", $validator->errors (        ));        } $user = $this->create ($request->all ());            if ($user->save ()) {$token = Jwtauth::fromuser ($user);                return $this->response->array ([token] and $token, "message" = "Registered Success",        "Status_code" = 201,]); } else {return $this->response->error ("User not Found... ", 404); }} protected function validator (array $data) {return Validator::make ($data, [' name ' = ' = ' requ Ired|unique:users ', ' email ' = ' required|email|max:255|unique:users ', ' Password ' and ' required| '    Min:6 ',]);            } protected function Create (array $data) {return user::create ([' name ' = = $data [' name '],    ' Email ' and $data [' email '], ' password ' + bcrypt ($data [' Password ']); }}

__
Login logincontroller.php

<?phpuse app\http\controllers\controller;use app\user;use dingo\api\routing\helpers;use Illuminate\Foundation\ Auth\authenticatesusers;use Illuminate\http\request;use Illuminate\support\facades\hash;use Symfony\Component\ Httpkernel\exception\unauthorizedhttpexception;use Tymon\jwtauth\facades\jwtauth;class LoginController extends    controller{use authenticatesusers;    Use Helpers; Public Function Login (Request $request) {$user = user::where (' email ', $request->email)->orwhere (' name ', $req        Uest->email)->first (); if ($user && hash::check ($request->get (' password '), $user->password)) {$token = Jwtauth::fromuse            R ($user);        return $this->sendloginresponse ($request, $token);    } return $this->sendfailedloginresponse ($request);        The Public Function sendloginresponse (Request $request, $token) {$this->clearloginattempts ($request);    return $this->authenticated ($token); } public FunctiOn authenticated ($token) {return $this->response->array ([' token '] = $token, ' Statu    S_code ' = +, ' message ' = ' User authenticated ',]);    } public Function Sendfailedloginresponse () {throw new Unauthorizedhttpexception ("Bad Credentials");    } Public Function Logout () {$this->guard ()->logout (); }}

__
Get user Information
routes/api.php

$api->group([‘middleware‘ => ‘api.auth‘], function ($api) {    $api->get(‘user‘, ‘App\Http\Controllers\Api\[email protected]‘);});php artisan make:controller Api/UsersController

Edit userscontroller.php

Header required for each request

Authorization :Bearer + token

Laravel 5.4+ Dingo +JWT Rapid Build API System

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.