This tutorial will guide you on how to create a restful crud API with passport auth in the Laravel 8 app, The passport auth is usually used to send information that can be trusted and verified using a digital signature.

In RESTful APIs, use the HTTP verbs/methods as actions, and the endpoints are the resources acted upon. will be using the HTTP verbs for their semantic meaning:

  • GETretrieve resources
  • POST: create resources
  • PUT: update resources
  • DELETEdelete resources

Now let’s start building a robust restful API in the Laravel 8 app using Passport Authentication. We will also show you a fully functional CRUD for user products using API.

This laravel 8 rest API crud tutorial with a passport; will make this kind of API using passport auth:

  • Login API
  • Register API
  • GetUser Info API
  • Update User API
  • Delete user API

Step 1: Create Laravel 8 App

First of all, Open a command prompt and run the following command to install laravel 8 app:

composer create-project --prefer-dist laravel/laravel laravelRestApi

Step 2: Database Configuration

Then, Navigate the root directory of your installed laravel restful authentication API with passport tutorial project. And open .env file. Then add the database details as follow:

 DB_CONNECTION=mysql 
 DB_HOST=127.0.0.1 
 DB_PORT=3306 
 DB_DATABASE=restapi //here your database name here
 DB_USERNAME=root //here database username here
 DB_PASSWORD=  //here database password here

Step 3: Install Laravel Passport

let us install Laravel Passport, Passport service provider registers its own database migration directory, this means that it creates the table that we will be needing for storing clients. The table will be used to store the token generated which will be used to identify a currently authenticated user. This token will then be attached to every request allowing each user access to protected routes.

composer require laravel/passport

After successfully install laravel passport, register providers. Open config/app.php. and put the bellow code :

  // config/app.php

'providers' =>[
 Laravel\Passport\PassportServiceProvider::class,
 ],

Now, you need to install laravel to generate passport encryption keys. This command will create the encryption keys needed to generate secure access tokens:

php artisan passport:install

Step 4: Passport Configuration

In this step, Navigate to App/Models directory and open User.php file. Then update the following code into User.php:

<?php

namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Passport\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var string[]
     */
    protected $fillable = ["name", "email", "password"];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array
     */
    protected $hidden = ["password", "remember_token"];

    /**
     * The attributes that should be cast.
     *
     * @var array
     */
    protected $casts = [
        "email_verified_at" => "datetime",
    ];
}

Next Register passport routes in App/Providers/AuthServiceProvider.php, Go to App/Providers/AuthServiceProvider.php and update this line => Register Passport::routes(); inside of boot method:

<?php

namespace App\Providers;

use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Gate;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [
        "App\Models\Model" => "App\Policies\ModelPolicy",
    ];

    /**
     * Register any authentication / authorization services.
     *
     * @return void
     */
    public function boot()
    {
        $this->registerPolicies();

        //
    }
}

Next, Navigate to config/auth.php and open auth.php file. Then Change the API driver to the session to passport. Put this code ‘driver’ => ‘passport’, in API :

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

Step 5: Run Migration

In this step, you need to do migration using the below command. This command creates tables in the database :

php artisan migrate

Step 6: Create Passport Auth and CRUD Controller

In this step, Create a controllers name UserAuthController . Use the below command and create a controller :

 php artisan make:controller Api/UserAuthController

After that, Create some authentication methods in UserAuthController.php. So navigate to app/http/controllers/API directory and open UserAuthController.php file. And, update the following methods into your UserAuthController.php file:

<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class UserAuthController extends Controller
{
    public function register(Request $request)
    {
        // $this->validate($request, [
        //     'name' => 'required|min:4',
        //     'email' => 'required|email',
        //     'password' => 'required|min:8',
        // ]);

        $user = User::create([
            "name" => $request->name,
            "email" => $request->email,
            "password" => bcrypt($request->password),
        ]);

        $token = $user->createToken("LaravelRestApi")->accessToken;

        return response()->json(
            [
                "data" => [
                    "type" => "activities",
                    "message" => "Success",
                    "data" => $token,
                ],
            ],
            200
        );
    }

    /**
     * Login Req
     */
    public function login(Request $request)
    {
        $data = [
            "email" => $request->email,
            "password" => $request->password,
        ];

        if (Auth::attempt($data)) {
            $user = Auth::user();
            $token = $user->createToken("LaravelRestApi")->accessToken;
            return response()->json(["token" => $token], 200);
        } else {
            return response()->json(["error" => "Unauthorised"], 401);
        }
    }

    public function userInfo()
    {
        $user = User::all();
        return response()->json(
            [
                "data" => [
                    "type" => "activities",
                    "message" => "Success",
                    "data" => $user,
                ],
            ],
            200
        );
    }

    public function update(Request $request, $id)
    {
        $user = User::find($id);
        $user->name = $request->name;
        $user->save();
        return response()->json(
            [
                "data" => [
                    "type" => "activities",
                    "message" => "Success",
                    "data" => $user,
                ],
            ],
            200
        );
    }
    public function delete(Request $request, $id)
    {
        $user = User::find($id);
        $user->delete();
        return response()->json(
            [
                "data" => [
                    "type" => "activities",
                    "message" => "Success",
                    "data" => "deleted!",
                ],
            ],
            200
        );
    }
}

Step 7: Create Auth and CRUD APIs Route

In this step, create rest API auth and crud operation routes.

So, navigate to the routes directory and open api.php. Then update the following routes into api.php file:

Route::post('register', [UserAuthController::class, 'register']);
Route::post('login', [UserAuthController::class, 'login']);

Route::prefix('/v1')->middleware('auth:api')->group(function () {
   Route::get('/user', [UserAuthController::class, 'userInfo']);
   Route::put('/user/{id}', [UserAuthController::class , 'update']);
   Route::delete('/user/{id}', [UserAuthController::class , 'delete']);
});

Then open a command prompt and run the following command to start the development server:

 php artisan serve

Step 8: Test Laravel 8 REST CRUD API with Passport Auth in Postman

Now, we will call above create crud and auth APIs in postman app:

 

ezgif-2-67afdcea77df

About the author
Code solution

info@codesolution.co.in

Discussion
  • 0 comments

Add comment To Login
Add comment