Laravel 9 Sanctum API Authentication Tutorial

  • 15-05-2022
  • 2163
  • Laravel 9
  • Haresh Chauhan

Watch Youtube Video (HINDI) :

In this tutorial, we'll make sanctum authentication for API in laravel.

Laravel provides sanctum authentication for single-page applications so if you want to create a single-page application then you can use sanctum authentication in your project.

In this tutorial, I will guide you on how to integrate sanctum authentication into your project. So here you need to follow step by step in a tutorial please follow one by one.

We need to make an example login API and get user details using sanctum.

In this example, we manage requests using sanctum authentication.

So let's do this example and make great sanctum authentication for your projects.

Step 1 : Install Sanctum

Here need to add laravel/sanctum So let's do it.

composer require laravel/sanctum

The sanctum configuration file will be placed in your application's config root directory.

Run the given below command in the terminal.

php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"

After installing the sanctum we need to migrate. So let's do it.

php artisan migrate

After done above configuration move to 2nd step.

Step 2 : Edit Kernel.php

This step needs to uncomment the given below line.

\Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class

change into the kernel.php file according to below given an example.

app/Http/Kernel.php

'api' => [
    \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
    'throttle:api',
    \Illuminate\Routing\Middleware\SubstituteBindings::class,
],

Step 3 : Modify User model

app/models/User.php

<?php
namespace App\Models;
 
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens; // Add this line in model
 
class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;
}

Step 4 : Create Controller

Now we have to create controller So, let's run command in terminal.

php artisan make:controller API\AuthController

app/Http/Controllers/API/AuthController.php

<?php
namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Validator;
use Auth;
class AuthController extends Controller
{
   public function userLogin(Request $request)
   {
       $input = $request->all();
        $vallidation = Validator::make($input,[
            'email' => 'required|email',
            'password' => 'required'
        ]);

        if($vallidation->fails()){
            return response()->json(['error' => $vallidation->errors()],422);
        }

        if (Auth::attempt(['email' => $input['email'],'password' => $input['password']])) {

            $user  = Auth::user();

            $token = $user->createToken('MyApp')->plainTextToken;

            return response()->json(['token' => $token]);
        }

   }

  public function userDetails()
  {
       $user  = Auth::user();
       return response()->json(['data' => $user]);
  }   

  public function logout(Request $request)
  {
      $request->user()->currentAccessToken()->delete();
      
      return response()->json(['success' => 'logout']);
  }
}

Make API routes like below example.

Step 5 : Create API Endpoint like below example

routes/api.php

<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\API\AuthController;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/

Route::post('login',[AuthController::class,'userLogin']);

Route::get('profile-details',[AuthController::class,'userDetails'])->middleware('auth:sanctum');
Route::get('logout',[AuthController::class,'logout'])->middleware('auth:sanctum');

After this we are ready to run our web application. Let's run given below command in your terminal

php artisan serve

Please check into postman like this please check snapshot and get your API response.

Login API

User Details API

Please set Bearer token and get auth response.

Logout API

Please set Bearer token and fire logout api.


We always thanks to you for reading our blogs.


dharmesh-image

Dharmesh Chauhan

(Swapinfoway Founder)

Hello Sir, We are brothers origin from Gujarat India, Fullstack developers working together since 2016. We have lots of skills in web development in different technologies here I mention PHP, Laravel, Javascript, Vuejs, Ajax, API, Payment Gateway Integration, Database, HTML5, CSS3, and Server Administration. So you need our service Please Contact Us

haresh-image

Haresh Chauhan

(Co-Founder)


We Are Also Recommending You :