[0] Open Project
Continue from previous post https://hashnotes.hashnode.dev/laravel-11-breeze
[1] Add API AuthController
[1.1] Create AuthController
php artisan make:controller Api/AuthController
[1.2] Edit AuthController
<?php
/* app\Http\Controllers\Api\AuthController.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;
use Illuminate\Validation\Rules;
use Illuminate\Support\Facades\Hash;
use Illuminate\Auth\Events\Registered;
class AuthController extends Controller
{
//
public function register(Request $request): JsonResponse
{
$request->validate([
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:'.User::class],
'password' => ['required', 'confirmed', Rules\Password::defaults()],
]);
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password),
]);
event(new Registered($user));
$created_user= User::where('email', '=', $request->email)->first();
return response()->json([
'user'=>$created_user,
'stus'=>'registered',
'verified'=>false], 200);
}
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_loggedin=[
'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_loggedin['user_token']= $token;
$user_loggedin['token_type']= 'Bearer';
$user_loggedin['verified']= true;
} else {
$user_loggedin['verified']= false;
}
return response()->json(
$user_loggedin,
200
);
}
}
[1.3] Install API Package
Laravel 11 requires API Package (Sanctum) to be installed first:
php artisan install:api
output:
...
- Installing laravel/sanctum (v4.0.2): Extracting archive
...
INFO Published API routes file.
...
INFO Running migrations.
2024_05_03_232650_create_personal_access_tokens_table ........................................ 11.21ms DONE
...
INFO API scaffolding installed. Please add the [Laravel\Sanctum\HasApiTokens] trait to your User model.
...
[1.4] Enable Has API feature in User Model
[1] Add use Laravel\Sanctum\HasApiTokens;
[2] Add HasApiTokens
<?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 HasFactory, Notifiable, HasApiTokens;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for serialization.
*
* @var array<int, 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.5] Edit API Route
Step [1.3] automatically creates the API route file.
Add AuthController class/methods to the API route:
(File: routes\api.php)
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
// Assigning middleware to individual route
//Route::get('/user', function (Request $request) {
// return $request->user();
//})->middleware('auth:sanctum');
use App\Http\Controllers\Api\AuthController;
// Registration route
Route::post('/register', [AuthController::class, 'register']);
// Login route
Route::post('/login', [AuthController::class, 'login']);
// Assigning middleware to group of routes
Route::middleware('auth:sanctum')->group(function () {
// Add your protected API routes here
// For example:
Route::get('/user', function (Request $request) {
return $request->user();
});
});
[2] Test
[2.1] Login
curl --location 'http://localhost/lara11breeze/public/api/login' `
--header 'Accept: application/json' `
--form '_method="POST"' `
--form 'name="alpha"' `
--form 'email="alpha@razzi.my"' `
--form 'password="your_password"'