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:

  1. Configure config/auth.php File: Open the config/auth.php file and make sure you have the following configurations for both the web and api guards:
php
// config/auth.php // ... 'guards' => [ 'web' => [ 'driver' => 'session', 'provider' => 'users', ], 'api' => [ 'driver' => 'token', 'provider' => 'users', 'hash' => false, ], ], // ...
  1. Define Authentication Providers: The default authentication provider for both the web and api guards is set to 'users', which corresponds to the users table in the database. Make sure you have the appropriate users table with the necessary columns for authentication.

  2. Use the web Guard for Web Routes: In your web routes (defined in routes/web.php), you can protect routes using the web 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'); });
  1. Use the api Guard for API Routes: In your API routes (defined in routes/api.php), you can protect routes using the api 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(); }); });
  1. Authentication Methods: When authenticating users, you can use the Auth facade to interact with the default guards:
php
use 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();
php
use 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.

Have questions or queries?
Get in Touch