I want to write a web service with laravel
I am trying to authenticate users and admin form users
table and admins
table respectively.
In this web service, user and admin authentication are different.
Authentication admins by email
& users by phone number
.Admins access Admin Panel by Web
routes and users use API
routes.
As I know Auth::attempt
is used to authenticate admins
from admins
table, but I want to authenticate another users from users
table and admin from admin
table.
Can anyone explain Multi Auth from more than two tables with example??
I know that
Auth::attempt
is used to authenticateusers
from users table but I changed the name.
What I have done so far
Guards
config/auth.php
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'admins',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
],
Providers
'providers' => [
'admins' => [
'driver' => 'eloquent',
'model' => App\Admin::class,
],
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
],
Routes
web.php (admins)
Route::group(['namespace' => 'Auth'] , function (){
// Authentication Routes...
$this->get('login', 'LoginController@showLoginForm')->name('login');
$this->post('login', 'LoginController@login');
$this->get('logout', 'LoginController@logout')->name('logout');
// Registration Routes...
$this->get('register', 'RegisterController@showRegistrationForm')->name('register');
$this->post('register', 'RegisterController@register');
// Password Reset Routes...
$this->get('password/reset', 'ForgotPasswordController@showLinkRequestForm')->name('password.request');
$this->post('password/email', 'ForgotPasswordController@sendResetLinkEmail')->name('password.email');
$this->get('password/reset/{token}', 'ResetPasswordController@showResetForm')->name('password.reset');
$this->post('password/reset', 'ResetPasswordController@reset');
});
api.php (users)
Route::group(['prefix' => 'android/v1' , 'namespace' => 'Api\Android\v1'] , function (){
$this->post('login' , 'UserController@login');
$this->post('register' , 'UserController@register');
});
UserController
api/android/v1/UserController.php
public function login(Request $request)
{
$validData = $this->validate($request, [
'mobile' => 'required|exists:users',
'password' => 'required'
]);
if(! auth()->attempt($validData)) {
return response([
'data' => 'data not true',
'status' => 'error'
],403);
}
return new UserResource(auth()->user());
}