menu

Wednesday 24 July 2019

how can write restful / authenticate API in Laravel latest version

Hope you have already install laravel with new version 5.5 or above

You can write restful authenticate API through the passport package using bellow command, So open your terminal and run bellow command:

$ composer require laravel/passport



After install successfully package, open config/app.php file and add service provider "PassportServiceProvider::class".
config/app.php'providers' =>[Laravel\Passport\PassportServiceProvider::class,],


Now we require to run the migration command 

After run migration command you will get several new tables in the database. If migration table is not there then run the command $ php artisan migrate:install

$ php artisan migrate

Run command and install the package.

$ php artisan passport:install

After successfully install passport package, we have to do the configuration on three place model, service provider and auth config file.

In the customer model, we need to add HasApiTokens class of Passport,
In the AuthServiceProvider we need to add “Passport::routes()”,
In the auth.php, we need to add an API auth configuration.

app/Customer.php
=================================
<?php
namespace App;
use Laravel\Passport\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
  use HasApiTokens, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
=============================================================
app/Providers/AuthServiceProvider.php
=============================================================
<?php
namespace App\Providers;
use Laravel\Passport\Passport; 
use Illuminate\Support\Facades\Gate; 
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
class AuthServiceProvider extends ServiceProvider 

    /** 
     * The policy mappings for the application. 
     * 
     * @var array 
     */ 
    protected $policies = [ 
        'App\Model' => 'App\Policies\ModelPolicy', 
    ];
/** 
     * Register any authentication / authorization services. 
     * 
     * @return void 
     */ 
    public function boot() 
    { 
        $this->registerPolicies(); 
        Passport::routes(); 
    } 
}
===========================================================
config/auth.php
===========================================================
<?php
return [
'guards' => [ 
        'web' => [ 
            'driver' => 'session', 
            'provider' => 'users', 
        ], 
        'api' => [ 
            'driver' => 'passport', 
            'provider' => 'users', 
        ], 
    ],
===========================================================
Create API Route
In this step, we will create API routes. Laravel provides api.php file for write web services route. So, let’s add a new route on that file.
===========================================================
routes/api.php
===========================================================
<?php
/* Define API Routes for call request */

Route::post('login', 'API\UserController@login');

Route::post('register', 'API\UserController@register');

Route::group(['middleware' => 'auth:api'], function(){

Route::post('details', 'API\UserController@details');

});
============================================================
Now we need to create new controler in API folder. CustomerController.php add code:
============================================================
<?php
namespace App\Http\Controllers\API;
use Illuminate\Http\Request; 
use App\Http\Controllers\Controller; 
use App\User; 
use Illuminate\Support\Facades\Auth; 
use Validator;
class CustomerController extends Controller 
{
public $successStatus = 200;
/** 
     * login api 
     * 
     * @return \Illuminate\Http\Response 
     */ 
    public function login(){ 
        if(Auth::attempt(['email' => request('email'), 'password' => request('password')])){ 
            $user = Auth::user(); 
            $success['token'] =  $user->createToken('MyApp')-> accessToken; 
            return response()->json(['success' => $success], $this-> successStatus); 
        } 
        else{ 
            return response()->json(['error'=>'Unauthorised'], 401); 
        } 
    }
/** 
     * 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 $this->sendError('Validation Error.', $validator->errors());       
        }


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


        return $this->sendResponse($success, 'Customer register successfully.');
    }
}
===============================================================
Almost every thing has done now ready to run commond:

$ php artisan serve

Laravel development server started: <http://127.0.0.1:8000>

Now you hit register and login API through Postman

http://localhost:8000/customer/register

{ "success": true, "data": { "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6ImQ4YzAxNDMzZWVjN2JlNDcxM2U5ZmI5NmE0ODM1MzJiNzAwYTY2YjJiOGE5YmE4MTNhMGU3NDAxNDJmYmJmZDJiZWY4ODFmZGUzMDkwYzRhIn0.eyJhdWQiOiIxIiwianRpIjoiZDhjMDE0MzNlZWM3YmU0NzEzZTlmYjk2YTQ4MzUzMmI3MDBhNjZiMmI4YTliYTgxM2EwZTc0MDE0MmZiYmZkMmJlZjg4MWZkZTMwOTBjNGEiLCJpYXQiOjE1NjM5NzYxMTQsIm5iZiI6MTU2Mzk3NjExNCwiZXhwIjoxNTk1NTk4NTE0LCJzdWIiOiI2Iiwic2NvcGVzIjpbXX0.V8o37YcjfNPmP6_afoWYsqyxHplcyjcHJdx0Y6k3LfWKmUTzs79gm-w-cm771b4GlBgZI5B-zm5hxan9ny8C_PxzH6Fpe_ztg_pD1LTJhPPg4y_JWKVpeleK8oZYgFHT_CewN43KF_ZWVJ_IRuxdXkeaj6sDkh2qt9iGJ2oXUQKLaxsVuWCBfXP2RDA5xgqCYDI-Qgr3nn_YiQq-dR1UxyJ1TPJdsOPo2Xdc4NsTTL__j7rnA_VUdK6aYTJ-ik4IJg4iytK1DNCNH1VHned3tHamRtGumM6wl6kiO2aHM5-CtOW1DWK65BIhaKLcdU9dT1S-8prsKIQRvL-HNAU1rRooPJS1vwuuK66dtb8Io877K4p92wA6psPv7tmvumNFvA_72kT3oycWsl91gaQl3D3ki7lP9PHvtObc63c4wEdFkEkgSrttgCfJ1Wa_D-_PDDjjMkTvr-82LiYjqBQIeyLxO93PGHjP4LAn-d4B8YDdzheHLsjK_0Cb1l03aKFTymsel0CQX-dtwJ-WA6CvFS7acJQQWHHQ-8-oAfRZds1LmzwgWAHmKiTaeAqXLjigUE4ll7apm7ywF7ZEkAgmk0vJ8zfM4jjZMPGFvIBfcfHd6O28FiPVD89u-wXAql-ijci_1syr5jKqgLfBcXtLjBnJWKI-vyXnK7z_5BZxDK8", "name": "Abc" }, "message": "Customer register successfully." }

http://localhost:8000/customer/login







1 comment: