Download Laravel App
https://laravel.com/docs/12.x/installation
Connecting our Database
open .env file root directory.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=8889
DB_DATABASE=laravel12dev
DB_USERNAME=root
DB_PASSWORD=root
Database Migration
php artisan migrate
myapp>php artisan migrate
Migration table created successfully.
check database table
Creating Controller
php artisan make:controller ApiController
myapp>php artisan make:controller ApiController
change it with the following codes:
app\Http\Controllers\ApiController.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 | //app\Http\Controllers\ApiController.php <?php namespace App\Http\Controllers\Api; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use Illuminate\Support\Facades\Hash; use App\Models\User; class ApiController extends Controller { public function register(Request $request ) { $request ->validate([ "name" => "required|string" , "email" => "required|string|email|unique:users" , "password" => "required|confirmed" // password_confirmation ]); User::create([ "name" => $request ->name, "email" => $request ->email, "password" => bcrypt( $request ->password) ]); // Response return response()->json([ "status" => true, "message" => "User registered successfully" ]); } public function login(Request $request ) { $request ->validate([ "email" => "required|string|email" , "password" => "required" ]); // Check user by email $user = User::where( "email" , $request ->email)->first(); // Check user by password if (! empty ( $user )) { if (Hash::check( $request ->password, $user ->password)) { // Login is ok $tokenInfo = $user ->createToken( "cairocoders-ednalan" ); $token = $tokenInfo ->plainTextToken; // Token value return response()->json([ "status" => true, "message" => "Login successful" , "token" => $token ]); } else { return response()->json([ "status" => false, "message" => "Password didn't match." ]); } } else { return response()->json([ "status" => false, "message" => "Invalid credentials" ]); } } // Profile (GET, Auth Token) public function profile() { $userData = auth()->user(); return response()->json([ "status" => true, "message" => "Profile information" , "data" => $userData ]); } // Logout (GET, Auth Token) public function logout() { // To get all tokens of logged in user and delete that request()->user()->tokens()-> delete (); return response()->json([ "status" => true, "message" => "User logged out" ]); } // Refresh Token (GET, Auth Token) public function refreshToken() { $tokenInfo = request()->user()->createToken( "newtokencairocdoers-ednalan" ); $newToken = $tokenInfo ->plainTextToken; // Token value return response()->json([ "status" => true, "message" => "Refresh token" , "acccess_token" => $newToken ]); } } |
Open project terminal and run this command,
php artisan install:api
After installation you will find this package into composer.json file,
"laravel/sanctum": "^4.0",
It will create “api.php” into /routes folder as well as it setup sanctum auth package.
Update “User.php” model file
Add this line,
use Laravel\Sanctum\HasApiTokens;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | //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<\Database\Factories\UserFactory> */ //use HasFactory, Notifiable; use HasApiTokens, HasFactory, Notifiable; /** * The attributes that are mass assignable. * * @var list<string> */ protected $fillable = [ 'name' , 'email' , 'password' , ]; /** * The attributes that should be hidden for serialization. * * @var list<string> */ protected $hidden = [ 'password' , 'remember_token' , ]; /** * Get the attributes that should be cast. * * @return array<string, string> */ protected function casts(): array { return [ 'email_verified_at' => 'datetime' , 'password' => 'hashed' , ]; } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | //routes\api.php use Illuminate\Http\Request; use Illuminate\Support\Facades\Route; use App\Http\Controllers\Api\ApiController; //Route::get('/user', function (Request $request) { // return $request->user(); //})->middleware('auth:sanctum'); Route::post( "register" , [ApiController:: class , "register" ]); Route::post( "login" , [ApiController:: class , "login" ]); // Protected Routes Route::group([ "middleware" => [ "auth:sanctum" ] ], function () { Route::get( "profile" , [ApiController:: class , "profile" ]); Route::get( "logout" , [ApiController:: class , "logout" ]); Route::get( "refresh-token" , [ApiController:: class , "refreshToken" ]); }); |
Form data –
{
"name": "cairocoders ednalan",
"email": "cairocoders@gmail.com",
"password": "123456",
"password_confirmation": "123456"
}
Login Method – POST URL – http://127.0.0.1:8000/api/login
Form data –
{
"email": "cairocoders@gmail.com",
"password": "123456"
}
Profile Method – GET URL – http://127.0.0.1:8000/api/profile
Header –
Accept:application/json
Authorization:Bearer
Refresh Token Method – GET URL – http://127.0.0.1:8000/api/refresh-token
Header –
Accept:application/json
Authorization:Bearer
Logout Method – GET URL – http://127.0.0.1:8000/api/logout
Header –
Accept:application/json
Authorization:Bearer