Laravel Passport: API implementation using Laravel Passport

Laravel Passport: API implementation using Laravel Passport

In this tutorial we will see about API implementation using Laravel Passport.

First of all we need to install passport. Install Passport via the Composer package manager.Please find below the command.

$ composer require laravel/passport

The Passport service provider registers its own database migration directory with the framework, so you should migrate your database after installing the package. The Passport migrations will create the tables your application needs to store clients and access tokens.Below command is for migrate.

$ php artisan migrate

Below command will create the encryption keys needed to generate secure access tokens.

$ php artisan passport:install

After running the passport:install command, add the Laravel\Passport\HasApiTokens trait to your App\User model.

namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Passport\HasApiTokens;

class User extends Authenticatable{
    use HasApiTokens, Notifiable;

Now we will call the Passport::routes method within the boot method of AuthServiceProvider. This method will register the routes necessary to issue access tokens and revoke access tokens, clients, and individual access tokens:

class AuthServiceProvider extends ServiceProvider{
    protected $policies = [
        'App\Model' => 'App\Policies\ModelPolicy',
    public function boot(){

Next, we will update config/auth.php configuration file, you should set the driver option of the api authentication guard to passport.

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

    'api' => [
        'driver' => 'passport',
        'provider' => 'users',

Now will create controller.Please find below the command to create a controller.

$ php artisan make:controller API/LoginController

Next, we will configure routes.


Register function is to registre new users.Below code is for register.

 public function register(Request $request){
        $validateData = $request->validate([
            'email' => 'required|email',
            'password' => 'required|min:5|max:20',
        $validateData['password'] = bcrypt($request->password);
        $user = User::create($validateData);
        $accessToken = $user->createToken('authToken')->accessToken;
        return response()->json(['user'=> $user,'access_token'=>$accessToken]);

Now we will test API through postman.If you want to know more about API testing through postman you can visit this link Test API through postman

Now will test our login process through postman. Below image for your reference.

Thank you for reading this post. we hope you like this Post, Please feel free to comment below, your suggestion. if you face any issue with this code let us know. We’d love to help! Stay tuned!