Reputation: 2806
I tried using guards for admins but its not working in Middleware in Laravel 11
. I have connected the MongoDB
with Laravel 11 for managing its database.
My admin login function looks like below where Auth::guard('admin')
is working fine:
public function login(Request $request){
if($request->isMethod('post')){
$data = $request->all();
if(Auth::guard('admin')->attempt(['email'=>$data['email'],'password'=>$data['password']])) {
//echo "<pre>"; print_r(Auth::guard('admin')->user()); die;
return redirect('admin/dashboard');
}else{
return redirect()->back()->with('error_message','Invalid Email or Password');
}
}
return view('admin.login');
}
But Auth::guard('admin')
is not working in Admin Middleware and I am not getting any data. My Admin Middleware file looks like below:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use Illuminate\Support\Facades\Route;
use Auth;
class Admin
{
/**
* Handle an incoming request.
*
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
*/
public function handle(Request $request, Closure $next): Response
{
// echo "<pre>"; print_r(Auth::guard('admin')->user()); die;
if(!Auth::guard('admin')->check()) {
return redirect('/admin/login');
}
return $next($request);
}
}
I have updated the auth.php file located at config\auth.php to set guards for admin to assign session in driver and admins in provider as shown below:
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'admin' => [
'driver' => 'session',
'provider' => 'admins',
],
],
Also set providers for admins to assign eloquent in driver and Admin classes in the model.
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => env('AUTH_MODEL', App\Models\User::class),
],
'admins' => [
'driver' => 'eloquent',
'model' => App\Models\Admin::class,
],
Due to the updates in Laravel 11, I added Admin Middleware in app.php file like below:
->withMiddleware(function (Middleware $middleware) {
$middleware->alias(['admin' => \App\Http\Middleware\Admin::class]);
})
My admin routes looks like below:
Route::prefix('/admin')->namespace('App\Http\Controllers\Admin')->group(function(){
//All the admin routes will be defined here...
Route::match(['get','post'],'login',[AdminController::class,'login']);
Route::group(['middleware'=>['admin']],function(){
Route::match(['get','post'],'dashboard',[AdminController::class,'dashboard']);
});
});
Upvotes: 0
Views: 480
Reputation: 2806
To resolve this issue, I have updated SESSION_DRIVER
as file
in .env
file.
So just minor change is required in .env
file like below:
Replace
SESSION_DRIVER=database
with
SESSION_DRIVER=file
Upvotes: 0