Here, I will learn you how to work with laravel sanctum API authentication example. you will learn laravel rest API using sanctum. you can see laravel sanctum REST API example.
Laravel Sanctum provides a simple authentication system for SPA (single page applications), mobile applications Or Web Application, and simple, token based APIs. Sanctum also allows each user of your application to generate multiple API tokens for their account.
Follow bellow few steps to create a restful API example in the laravel app.
Step 1: Install Laravel
This step is not required; however, if you have not created the laravel app, then you may go ahead and execute the below command:
composer create-project laravel/laravel token-base-api
Second step is not required because laravel by default provided sanctum package manager in case is not install then you can use step 2
Step 2: Use Sanctum
In this step we need to install sanctum via the Composer package manager, so one your terminal and fire bellow command:
composer require laravel/sanctum
After successfully install sanctum package, we need to publish configuration file with following command:
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
we require to get default migration for create new sanctum tables in our database. so let's run bellow command.
php artisan migrate
Next, we need to add middleware for sanctum api, so let's add as like bellow:
app/Http/Kernel.php
....
'api' => [
\Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
....
Step 3: Sanctum Configuration
In this step, we have to configuration on three place model, service provider and auth config file. So you have to just following change on that file.
app/Models/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\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',
];
}
we are adding HasApiTokens class of Sanctum in User Models
Now we are adding a api.php file guard in auth file inside guards
..........
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
],
..........
Step 4: Create API Routes
In this step, we will create api routes for login, register and products rest api. So, let's add new route on that file.
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Api\V1\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::group(['prefix'=>'v1/'], function(){
Route::group(['prefix'=>'auth'], function(){
Route::post('/signin', [AuthController::class,'signin']);
Route::post('/signup', [AuthController::class,'signup']);
});
});
//auth
Route::group(['prefix'=>'auth','middleware' => ['auth:sanctum']], function(){
Route::get('/logout', [AuthController::class,'logout']);
Route::get('/', [UserController::class,'index']);
});
Step 5: Create Controller Files
in next step, now we have create new controller as AuthController, i created new folder "Api/V1" in Controllers folder because we will make alone APIs controller, So let's create :
<?php
namespace App\Http\Controllers\Api\V1;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
class AuthController extends Controller
{
public function __construct() {
}
/*
* @metod signin()
* @param number limit 10 digit
* @fiels ['user_mobile','user_password']
* @about This Method use for login for user
*/
public function signin(Request $request){
$validation = Validator::make($request->all(),[
'user_mobile_or_email' => 'required',
'user_password' => 'required',
]);
if($validation->fails()){
return response()->json(['status' =>false,'message' =>$validation->errors()->first()],422);
}
try {
$user = User::where(function($query) use ($request){
$query->where('user_mobile',$request->user_mobile_or_email);
})->orWhere(function($query) use ($request){
$query->where('user_email',$request->user_mobile_or_email);
});
$user = $user->first();
if(!$user){
return response()->json(['status' =>false,'message' => 'Username is incorrect please try again !'],200);
}
if(!Hash::check($request->user_password,$user->user_password)){
return response()->json(['status' =>false,'message' => 'Password is incorrect please try again !'],200);
}
$token = $user->createToken("personal access token")->plainTextToken;
return response()->json(['status' =>true,'message' => 'Signin Successfully !','data'=>$user,'token'=>$token],200);
} catch (\Exception $e) {
return response()->json(['status' =>false,'message' => 'There was an error while processing your request: ' .
$e->getMessage()],500);
}
}
/*
* @metod signup()
* @param number limit 10 digit
* @fiels ['user_mobile','user_email']
* @about This Method use for signup and register for user
*/
public function signup(Request $request){
$validation = Validator::make($request->all(),[
'user_mobile' => 'required',
'user_password'=>'required'
]);
if($validation->fails()){
return response()->json(['status' =>false,'message' =>$validation->errors()->first()],422);
}
try {
$user = new User();
$user->user_mobile = $request->user_mobile;
$user->user_email = $request->user_email;
$user->user_password = Hash::make($request->user_password);
$user->user_type = 'customer';
$user->save();
return response()->json(['status' =>true,'message' => 'User Registerd successfully !'],200);
} catch (\Exception $e) {
return response()->json(['status' =>false,'message' => 'There was an error while processing your request: ' .
$e->getMessage()],500);
}
}
/*
* @metod logout()
* @param
* @fiels
* @about This Method use for logout customers
*/
public function logout(Request $request){
try {
//To do fcm remove
$request->user()->token()->revoke();
return response()->json(['status' =>true,'message' => 'Sign Out successfully !'],200);
} catch (\Exception $e) {
return response()->json(['status' =>false,'message' => 'There was an error while processing your request: ' .
$e->getMessage()],500);
}
}
}
Step 6: Create API Routes
in next step, now we have create new controller as UserController, i created new folder "Api/V1" in Controllers folder because we will make alone APIs controller, So let's create and get user by aouth token:
<?php
namespace App\Http\Controllers\Api\V1;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\User;
class UserController extends Controller
{
/*
* @metod index()
* @param token
* @fiels ['token']
* @about This Method use for fetch user details
*/
public function index(Request $request){
$user = $request->user();
try {
if($user->count() > 0){
return response()->json(['status' =>true,'message' => 'Data found !','data'=> $user],200);
}else{
return response()->json(['status' =>false,'message' => 'Data not found !'],200);
}
} catch (\Exception $e) {
return response()->json(['status' =>false,'message' => 'There was an error while processing your request: ' .
$e->getMessage()],500);
}
}
}
Step 7: Test Api With Token