As I know Auth::attempt is used to authenticate users from users table, but i want to authenticate another users from students table and teachers from teachers table. How to create multiple authentication for different users? I'm new in laravel api's
My Answer:
In Laravel, you can create multiple authentication guards to authenticate users from different tables. Here's how you can achieve this in Laravel 8 API:
1. Define new guards in `config/auth.php` file:
php
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
'student' => [
'driver' => 'token',
'provider' => 'students',
],
'teacher' => [
'driver' => 'token',
'provider' => 'teachers',
],
],
2. Define new providers in `config/auth.php` file:
php
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
'students' => [
'driver' => 'eloquent',
'model' => App\Models\Student::class,
],
'teachers' => [
'driver' => 'eloquent',
'model' => App\Models\Teacher::class,
],
],
3. Use the `auth` middleware with the desired guard in your routes:
php
Route::middleware('auth:student')->get('/student', function (Request $request) {
return $request->user();
});
Route::middleware('auth:teacher')->get('/teacher', function (Request $request) {
return $request->user();
});
4. Authenticate users using the desired guard in your controller:
php
if (Auth::guard('student')->attempt($credentials)) {
// Authentication passed for student
}
if (Auth::guard('teacher')->attempt($credentials)) {
// Authentication passed for teacher
}
By following these steps, you can authenticate users from different tables using multiple guards in Laravel 8 API.
Rate this post
5 of 5 based on 9626 votesComments