Table of Contents
Inside this article we will one more important concept of laravel i.e REST api development in laravel 8 with Sanctum authentication. This will be step by step guide to create restful services from scratch.
We will create a secure set of API Authentication using Laravel 8 Sanctum. Sanctum is a laravel composer package.
What we will do in this article –
- User Register API
- Login API
- User Profile API
- Logout API
Above are the apis, we will create using sanctum authentication. This will be very interesting to learn.
To Learn API development in Laravel 8 Using Passport, Click here.
API development in Laravel 8 Using JWT Authentication, Click here.
Let’s get started.
Installation of Laravel 8 Application
Laravel Installation can be done in two ways.
- Laravel Installer
- By using composer
Laravel Installer
To install Laravel via Laravel installer, we need to install it’s installer first. We need to make use of composer for that.
$ composer global require laravel/installer
This command will install laravel installer at system. This installation is at global scope, so you type command from any directory at terminal. To verify type the given command –
$ laravel
This command will open a command palette of Laravel Installer.
To create ad install laravel project in system,
$ laravel new blog
With the name of blog a laravel project will be created at your specified path.
By using composer
Alternatively, we can also install Laravel by Composer command create-project. If your system doesn’t has Composer Installed, Click here to Install Composer ? Here is the complete command to create a laravel project-
$ composer create-project --prefer-dist laravel/laravel blog
After following these steps we can install a Laravel 8 application into system. To start the development server of Laravel –
$ php artisan serve
This command outputs –
Starting Laravel development server: http://127.0.0.1:8000
Assuming laravel 8 already installed at system.
Create Database & Connect
To create a database, either we can create via Manual tool of PhpMyadmin or by means of a mysql command.
CREATE DATABASE laravel_app;
To connect database with application, Open .env file from application root. Search for DB_ and update your details.
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=laravel_app DB_USERNAME=root DB_PASSWORD=root
Install And Configure Laravel Sanctum Auth
Laravel Sanctum provides a featherweight authentication system for SPAs (single page applications), mobile applications, and simple, token based APIs.
Open project into terminal and run this command.
$ composer require laravel/sanctum

Publish Sanctum Package
Run this command to publish package.
$ php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
This will create a sanctum.php file in the /config directory, as well as the necessary migration files in the /database/migrations directory.
Migrate Migration Files
$ php artisan migrate
Setup User Model
Open User.php from /app/Models and write this following code into it.
<?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\Sanctum\HasApiTokens; class User extends Authenticatable { use HasFactory, Notifiable, HasApiTokens; /** * 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', ]; /** * The attributes that should be cast to native types. * * @var array */ protected $casts = [ 'email_verified_at' => 'datetime', ]; }
Create Authentication Controller
Open project into terminal and run this artisan command.
$ php artisan make:controller AuthController
It will create a file AuthController.php at /app/Http/Controllers folder.
Open AuthController.php file and write this following code into it.
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Hash; use App\Models\User; use Illuminate\Support\Facades\Auth; class AuthController extends Controller { public function register(Request $request) { $validatedData = $request->validate([ 'name' => 'required|string|max:255', 'email' => 'required|string|email|max:255|unique:users', 'password' => 'required|string|confirmed|min:6', ]); $user = User::create([ 'name' => $validatedData['name'], 'email' => $validatedData['email'], 'password' => Hash::make($validatedData['password']), ]); $token = $user->createToken('auth_token')->plainTextToken; return response()->json([ 'message' => "User registered successfully", 'access_token' => $token, 'token_type' => 'Bearer', ]); } public function login(Request $request) { if (!Auth::attempt($request->only('email', 'password'))) { return response()->json([ 'message' => 'Invalid login details' ], 401); } $user = User::where('email', $request['email'])->firstOrFail(); $token = $user->createToken('auth_token')->plainTextToken; return response()->json([ 'access_token' => $token, 'token_type' => 'Bearer', 'message' => "User logged in successfully", ]); } public function profile(Request $request) { return $request->user(); } public function logout(Request $request) { auth()->user()->tokens()->delete(); return response()->json(['message' => 'User successfully signed out']); } }
Update RouteServiceProvider File
Open RouteServiceProvider.php from /app/Providers folder. Uncomment this line from file.
protected $namespace = 'App\\Http\\Controllers';
Create Authentication Routes
Open api.php from /routes folder.
# Add to header use App\Http\Controllers\AuthController; Route::post('register', [AuthController::class, 'register']); Route::post('login', [AuthController::class, 'login']); Route::group(['middleware' => ['auth:sanctum']], function () { Route::post('profile', [AuthController::class, 'profile']); Route::post('logout', [AuthController::class, 'logout']); });
Application Testing
Open project to terminal and type the command to start development server
$ php artisan serve
Register API – http://127.0.0.1:8000/api/register
Method – POST
Body
{ "name": "Sanjay Kumar", "email": "sanjay@gmail.com", "password": "123456", "password_confirmation": "123456" }
Header
Content-Type:application/json Accept:application/json

Login API – http://127.0.0.1:8000/api/login
Method – POST
Body
{ "email": "sanjay@gmail.com", "password": "123456" }
Header
Content-Type:application/json Accept:application/json

User Profile API – http://127.0.0.1:8000/api/profile
Method – POST
Header
Content-Type:application/json Accept:application/json Authorization: Bearer <Token>

Logout API – http://127.0.0.1:8000/api/logout
Method – POST
Header
Content-Type:application/json Accept:application/json Authorization: Bearer <Token>

We hope this article helped you to learn about API Authentication using Laravel 8 Sanctum Tutorial in a very detailed way.
If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.
Find More on Laravel 8 Articles here
- How to Create Multi Language Website in Laravel 8
- How To Read XML File in Laravel 8 – Example
- How To Upload And Save XML Data in Laravel 8
- Laravel 8 Ajax Post Request Tutorial
- Laravel 8 Authentication using Jetstream with Inertia Js
- Laravel 8 Authentication using Jetstream with Livewire
- Laravel 8 Authentication with Breeze Tutorial
- Laravel 8 Clear Cache of Route, View & Config
- Laravel 8 Cron Job Task Scheduling Tutorial
- Laravel 8 DataTable Ajax Pagination with Search And Sort
- Laravel 8 Firebase Push Notification Tutorial
- Laravel 8 Form Validation Methods
- Laravel 8 Installation Guide – PHP Framework
- Laravel 8 Layouts And Views Complete Guide
- Laravel 8 Routing Tutorial Step by Step Guide
- Laravel 8 Send Mail using Gmail SMTP Server
- Laravel 8 Send Push Notification to Android Using Firebase
- Laravel 8 Send Push Notification to IOS Using Firebase
- Laravel 8 Stub Customization
Hi, I am Sanjay the founder of ONLINE WEB TUTOR. I welcome you all guys here to join us. Here you can find the web development blog articles. You can add more skills in web development courses here.
I am a Web Developer, Motivator, Author & Blogger. Total experience of 7+ years in web development. I also used to take online classes including tech seminars over web development courses. We also handle our premium clients and delivered up to 50+ projects.