Here is a tutorial on how to authenticate REST APIs in Laravel 10 using Sanctum:
- Install Laravel 10.
- Install the Sanctum package.
composer require laravel/sanctum
- Add the Sanctum middleware to the
api
guard in theconfig/auth.php
file.
'api' => [
'driver' => 'sanctum',
],
- Create a user model and migrate the database.
- Create a route to your controller.
Route::post('/api/login', 'AuthController@login');
- Create a controller to handle the login request.
PHP
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class AuthController extends Controller
{
public function login(Request $request)
{
$credentials = $request->validate([
'email' => 'required|email',
'password' => 'required',
]);
if (Auth::attempt($credentials)) {
return response()->json(['success' => true]);
}
return response()->json(['error' => 'Unauthorized'], 401);
}
}
- Test the route. In your terminal, run the following command to test the route:
php artisan serve
Then, open a browser and navigate to the following URL:
http://localhost:8000/api/login
Enter your email address and password and click on the “Login” button. If the login is successful, you will receive a JSON response with a success message.
Here is an explanation of the code:
- The
validate()
method validates the request data. - The
attempt()
method attempts to authenticate the user with the given credentials. - The
json()
method returns a JSON response.