In Laravel, you can use two default guards to handle authentication for different types of users or authentication scenarios. By default, Laravel provides a web
guard for handling web-based authentication and an api
guard for handling stateless API authentication. Here's how you can use both guards in your Laravel application:
- Configure
config/auth.php
File: Open theconfig/auth.php
file and make sure you have the following configurations for both theweb
andapi
guards:
php// config/auth.php
// ...
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
'hash' => false,
],
],
// ...
Define Authentication Providers: The default authentication provider for both the
web
andapi
guards is set to'users'
, which corresponds to theusers
table in the database. Make sure you have the appropriateusers
table with the necessary columns for authentication.Use the
web
Guard for Web Routes: In your web routes (defined inroutes/web.php
), you can protect routes using theweb
guard middleware. This will handle session-based authentication for web routes.
php// routes/web.php
Route::group(['middleware' => 'auth:web'], function () {
// Your protected web routes go here
Route::get('/dashboard', 'DashboardController@index');
});
- Use the
api
Guard for API Routes: In your API routes (defined inroutes/api.php
), you can protect routes using theapi
guard middleware. This will handle token-based authentication for API routes.
php// routes/api.php
Route::group(['middleware' => 'auth:api'], function () {
// Your protected API routes go here
Route::get('/user', function (Request $request) {
return $request->user();
});
});
- Authentication Methods:
When authenticating users, you can use the
Auth
facade to interact with the default guards:
phpuse Illuminate\Support\Facades\Auth;
// Log in a user using the 'web' guard
Auth::guard('web')->login($user);
// Log out a user from the 'web' guard
Auth::guard('web')->logout();
// Get the currently authenticated user from the 'web' guard
$user = Auth::guard('web')->user();
phpuse Illuminate\Support\Facades\Auth;
// Log in a user using the 'api' guard
Auth::guard('api')->login($user);
// Log out a user from the 'api' guard
Auth::guard('api')->logout();
// Get the currently authenticated user from the 'api' guard
$user = Auth::guard('api')->user();
By using the two default guards, you can handle web-based and API-based authentication separately, allowing you to implement different authentication mechanisms as per your requirements. Remember to use the appropriate middleware (auth:web
and auth:api
) to protect your routes and APIs based on the type of authentication you need.