Laravel 10 Sanctum API Authentication Tutorial Example

  • 22-02-2023
  • 4879
  • Laravel 10
  • Haresh Chauhan

Watch Youtube Video (HINDI) :

Hello guys, today in this post we will integrate Laravel 10 Sanctum API Authentication Tutorial Example, I will tell you from scratch how to integrate laravel 10 sanctum API authentication step-by-step guidelines.

Using laravel 10 sanctum API we will authenticate the user, also we will generate auth token using sanctum, get the user data to form that token and we will make a logout API.

So if you want to learn how to integrate sanctum API in laravel 10, this post will help you with all the guideline step by step. Laravel sanctum API authentication is a powerful tool to make your API secure and collective API.

Laravel 10 Sanctum API Authentication Steps :

  • Step 1. Install Project.
  • Step 2. Database Configuration.
  • Step 3. Add Sanctum Composer.
  • Step 4. Add HasApiTokens User Model.
  • Step 5. Make Controller.
  • Step 6. Route Define.
  • Step 7. Run Seeder (Dummy Data).
  • Step 8. Start Server.

Step 1. Install Project

In this step, we will clone the new fresh laravel project, If you have already Install skip this step and move forward to the next step.

composer create-project laravel/laravel example-app

Step 2. Database configuration

Once you successfully installed the laravel 10 project we will add database configuration in the ".env" file. this file you will see at the root of the application.


Step 3. Add Sanctum Composer

Now we will add the sanctum composer package to the laravel app. use the below command and install the package, this will add core library files to your laravel 10 app. this package takes sometime the install.

composer require laravel/sanctum

After the composer is installed, we will migrate the database, use the below command and migrate your database.

php artisan migrate

Add this API attribute in the "app/Http/Kernel.php", It might be already added, you just need to remove comment from the attribute code.

'api' => [
    \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class, // REMOVE COMMENT

Step 4. Add HasApiTokens User Model

Now we will add HasApiTokens in the user model, using Laravel\Sanctum\HasApiTokens, basically by default laravel is provided already but still you just check whether the line was added or not also in the Model class just use it.

Api configuration in the model for the sanctum token already has the laravel model configuration provided, you may not need to do any changes. you just check there if anything missing then and then config it.


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\Sanctum\HasApiTokens; // ADD THIS

class User extends Authenticatable
    use HasApiTokens, HasFactory, Notifiable; // ADD THIS

     * The attributes that are mass assignable.
     * @var array
    protected $fillable = [

     * The attributes that should be hidden for serialization.
     * @var array
    protected $hidden = [

     * The attributes that should be cast.
     * @var array
    protected $casts = [
        'email_verified_at' => 'datetime',

Step 5. Make Controller

Now we will create a UserController, use the below command, and create a controller with the new method of making a controller.

php artisan make:controller   

Name : API/UserController

Press : 1 // FOR API

Model : User

Copy the whole Usercontroller code and paste it into your UserController, In this UserController there are three methods defined.


namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Auth;
use Validator;

class UserController extends Controller
     * Display a listing of the resource.
    public function loginUser(Request $request): Response
        $validator = Validator::make($request->all(), [
            'email' => 'required|email',
            'password' => 'required',

            return Response(['message' => $validator->errors()],401);

            $user = Auth::user(); 
            $success =  $user->createToken('MyApp')->plainTextToken; 
            return Response(['token' => $success],200);

        return Response(['message' => 'email or password wrong'],401);

     * Store a newly created resource in storage.
    public function userDetails(): Response
        if (Auth::check()) {

            $user = Auth::user();

            return Response(['data' => $user],200);

        return Response(['data' => 'Unauthorized'],401);

     * Display the specified resource.
    public function logout(): Response
        $user = Auth::user();

        return Response(['data' => 'User Logout successfully.'],200);

Step 6. Route Define

Define router in your api.php file, this file is located in the routes folder from the root.


use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\API\UserController;
| API Routes
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider and all of them will
| be assigned to the "api" middleware group. Make something great!

Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();


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

Step 7. Run Seeder (Dummy Data)

For making dummy data in the user table we will make a seeder, this seeder will generate defined user data in the database. copy this seeder method and paste it into your DatabaseSeeder.php file.


namespace Database\Seeders;

// use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
        * Seed the application's database.
    public function run(): void

            'name' => 'Test User',
            'email' => '',
            'password' => bcrypt(123)

Now we will run the seeder, use the given command in your command prompt and generate dummy data.

php artisan db:seed

Step 8. Start Server

Start the development server using the below command.

php artisan serve

Run this API in your postman with the email and password field in the payload with the POST method below the example given.



For getting user data from the logged-in user we will fire the below-given API, with this API we will pass the generated token. Based on this token server side identify the user and will return user data from the auth.



If you want to logout of the current user, we will destroy that user token from the database. so the user can log out of the system and able to log in again. use the given API and logout the user from the system.



We always thanks to you for reading our blogs.


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 Chauhan


We Are Also Recommending You :