My question is simple I want to have multi auth (for user + admin) in my laravel app using guard, so I can in the controller simply check if the authenticated user is admin or not, like this:
public function addCategories(Request $request) {
if (!Auth::guard('admin')->check()) {
abort(404);
}
....
}
But the code above always return false, don't know why, and this is my admin login:
public function doLogin(Request $request) {
try {
$validator = \Validator::make($request->post(), [
'username' => array(
'required',
'string',
'max:12',
'regex:/(^[A-Za-z0-9_]+$)+/'
),
'password' => 'required|max:12'
]);
if ($validator->fails()) {
//$validator->errors()
throw new Exception('post data are incorrect');
}
$admin = Admin::where('AUsername', '=', $request->post('username'))
->first();
if ($admin == null) {
throw new Exception('username or password are incorrect');
} else if (!\Hash::check($request->post('password'), $admin->toArray()['APassword'])) {
throw new Exception('username or password are incorrect');
}
Auth::guard('admin')->login($admin);
if (!Auth::guard('admin')->check()) {
throw new Exception('could not login, please try again later');
}
return response()->json([
'success' => 'login success'
]);
} catch(Exception $e) {
return response()->json(
['error' => $e->getMessage()]
);
}
}
By the way I didn't user (Auth::attempt()), because it always faild (returned false))
And finally this is my auth.php:
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
'admin' => [
'driver' => 'session',
'provider' => 'admins',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'admins' => [
'driver' => 'eloquent',
'model' => App\Admin::class,
],
],
you should extend admin model from Authenticatable instead of eloquent model and call auth:admin middleware for your routes that need admin permission also this link can help you multi-auth in laravel