Laravel - Create Sanctum Token for User Login API
[1] Open the Laravel Project
Continue from the previous tutorial https://hashnotes.hashnode.dev/laravel-add-additional-fields-to-user-profile
[2] Create API Controllers
[2.1] Create API Controllers via Laragon CMDER Console
This tutorial focuses only on login and token creation process using AuthController method.
The ProfileController method is declared for future use.
Api/AuthController
php artisan make:controller Api/AuthController
Api/ProfileController
php artisan make:controller Api/ProfileController
Outcome:
[3] Edit AuthController
Begin with login processing.
[3.1] Add login method
(file: app\Http\Controllers\Api\AuthController.php)
<?php
namespace App\Http\Controllers\Api;
use App\Models\User;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Auth;
class AuthController extends Controller
{
//
public function login(Request $request)
{
if (!Auth::attempt($request->only("email", "password"))) {
return response()->json(
[
"user" => Null,
"message" => "Invalid login details",
"stus" => "failed",
],
200
);
}
$user = User::where("email", $request["email"])->firstOrFail();
$user_out=[
'id' => $user->id,
'email' => $user->email,
'email_verified_at'=> $user->email_verified_at,
'stus'=>'loggedin'
];
if ($user->email_verified_at != Null) {
$user_out['verified']= true;
} else {
$user_out['verified']= false;
}
return response()->json(
$user_out,
200
);
}
}
[4] Update API Routes
(file: routes\api.php )
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Api\AuthController;
/* this is automatically created by laravel */
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});
/* this is created for login via Api\AuthController */
Route::post('login', [AuthController::class, 'login'])
->name('apilogin');
[5] Test Login API
The following is the CURL codes for Windows console. If you want to run on Linux, replace the backtick `
with backslash \
.
curl --location 'http://localhost/rearnet/public/api/login' `
--header 'Accept: application/json' `
--header 'Content-Type: application/json' `
--data-raw '{
"email": "adam@razzi.my",
"password": "aaaaaaaa"
}'
Outcome:
[6] Add Sanctum Token feature
[6.1] Check that the User Model has Sanctum feature enabled
(file: app\Models\User.php)
Laravel may have already inserted Sanctum feature as shown below.
<?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 implements MustVerifyEmail
{
use HasApiTokens, HasFactory, Notifiable;
[6.2] Update the login method with token feature
(file: app\Http\Controllers\Api\AuthController.php)
Add the following items:
$token = $user->createToken("auth_token")->plainTextToken;
$user_out['user_token']= $token;
$user_out['token_type']= 'Bearer';
<?php
namespace App\Http\Controllers\Api;
use App\Models\User;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Auth;
class AuthController extends Controller
{
//
public function login(Request $request)
{
if (!Auth::attempt($request->only("email", "password"))) {
return response()->json(
[
"user" => Null,
"message" => "Invalid login details",
"stus" => "failed",
],
200
);
}
$user = User::where("email", $request["email"])->firstOrFail();
$user_out=[
'id' => $user->id,
'email' => $user->email,
'email_verified_at'=> $user->email_verified_at,
'stus'=>'loggedin'
];
if ($user->email_verified_at != Null) {
$token = $user->createToken("auth_token")->plainTextToken;
$user_out['user_token']= $token;
$user_out['token_type']= 'Bearer';
$user_out['verified']= true;
} else {
$user_out['verified']= false;
}
return response()->json(
$user_out,
200
);
}
}
Test the login API again.
The response shall contain the user_token
parameter.
[6.3] Test Token
Since Laravel has already included a sample code for testing the API (refer step 4), we will test the token that we received in the step 6.2 above.
Send CURL request as follows:
curl --location 'http://localhost/rearnet/public/api/user' `
--header 'Authorization: Bearer 1|V4wphGTktJvvsG6S1yIXmUa5xlxvcNeSFcapjBVad6d3a80a'
Outcome:
The token has been recognized by the server so it returns the user information.