Remon Hasan
Posted on May 16, 2021
Source Code
Laravel Sanctum, formerly known as Airlock, is a Laravel package created for the authentication of Single Page Applications (SPAs), mobile applications, and basic token-based APIs. It can be used to issue API Tokens to your users and authenticate Single Page Applications using Laravel's session.
we are going to create product api. For testing we will use the postman.
Model and Migration
First, we have to create a product model,migration,controller as like:
php artisan make:model Product -m
php artisan make:controller ProductController --api
Create the fields as like:
Migrate: Before migrate you should create the database in env file and connect to the MySql server or others you prefer.
php artisan migrate
Route
Second, we have to create a resource route in api.php as like:
Route::resource('products', ProductController::class);
Controller Functions
Postman Test
Create:
Update:
Validation:
Delete:
Search by Name:
Get by ID:
Sanctum Authentication and Access Token Generation
Install Sanctum:
composer require laravel/sanctum
Vendor Publish for access token migration:
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
Migrate:
php artisan migrate
setup
Go to app, then kernel.php and add the given lines in api array section. also for query you can follow laravel Sanctum Documentation
Add to User Model: Go to User.php and add the lines:
use Laravel\Sanctum\HasApiTokens;
use HasFactory, Notifiable, HasApiTokens;
Create a group route function which will include the protected routes:
Create Controller
php artisan make:controller AuthController
Register Function
Postman Test:
Get Product access by token:
Now add logout: After logout the token will be deleted.
`public function logout(Request $request) {
auth()->user()->tokens()->delete();
return [
'message' => 'Logged out'
];
}`
Create logout route:
Route::post('/logout', [AuthController::class, 'logout']);
Postman Test:
Login
Create route for login as like:
Route::post('/login', [AuthController::class, 'login']);
Login Function:
Logged in:
All Public and Protected Route
Posted on May 16, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.