i am trying to make authentication of laravel with middleware but my middleware not working to redicrect to admin/dashboard page
my code below
have data in data base that roll_as is 1 and i trying to login as admin but when i give input of login credentials of login then middleware redirect me on /home page
help me
my all code is below
// ths is tha adminMiddleware
<?php
namespace AppHttpMiddleware;
use Closure;
use IlluminateHttpRequest;
use SymfonyComponentHttpFoundationResponse;
use IlluminateSupportFacadesAuth;
class AdminMiddleware
{
/**
* Handle an incoming request.
*
* @param Closure(IlluminateHttpRequest): (SymfonyComponentHttpFoundationResponse) $next
*/
public function handle(Request $request, Closure $next): Response
{
if(!Auth::user()->roll_as =='1'){
return redirect('/home')->with('status','Access Denied Becouse You Are Not Admin This Acces Only For Admin');
}
return $next($request);
}
}
/// LoginController
<?php
namespace AppHttpControllersAuth;
use AppHttpControllersController;
use IlluminateSupportFacadesAuth;
use AppProvidersRouteServiceProvider;
use IlluminateFoundationAuthAuthenticatesUsers;
use IlluminateHttpRequest;
use IlluminateAppHttpMiddlewareAuthenticate;
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* @var string
*/
// protected $redirectTo = RouteServiceProvider::HOME;
protected function authenticated()
{
if(Auth::user()->roll_as=='1'){
return redirect('admin/dashboard')->with('status','Welcome Admin');
}
else{
return redirect('/home')->with('status','Welocome You are logged In Succesfully');
}
}
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
}
//web.php
<?php
use IlluminateSupportFacadesRoute;
use IlluminateSupportFacadesAuth;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider and all of them will
| be assigned to the "web" middleware group. Make something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::get('/home', [AppHttpControllersHomeController::class, 'index'])->name('home');
Route::group(['prefix' => 'admin','middleware'=>(['auth','asAdmin'])], function () {
Route::get('dashboard', [AppHttpControllersAdminDashboardController::class,'index']);
});
//kernal.php
*/
protected $middlewareAliases = [
'auth' => AppHttpMiddlewareAuthenticate::class,
'auth.basic' => IlluminateAuthMiddlewareAuthenticateWithBasicAuth::class,
'auth.session' => IlluminateSessionMiddlewareAuthenticateSession::class,
'cache.headers' => IlluminateHttpMiddlewareSetCacheHeaders::class,
'can' => IlluminateAuthMiddlewareAuthorize::class,
'guest' => AppHttpMiddlewareRedirectIfAuthenticated::class,
'password.confirm' => IlluminateAuthMiddlewareRequirePassword::class,
'signed' => AppHttpMiddlewareValidateSignature::class,
'throttle' => IlluminateRoutingMiddlewareThrottleRequests::class,
'verified' => IlluminateAuthMiddlewareEnsureEmailIsVerified::class,
'asAdmin' => AppHttpMiddlewareAdminMiddleware::class,
];
i am trying to make middleware and this middleware not working
please help me
2
Answers
I think the condition on your middleware is wrong. The
!Auth::user()->roll_as
I think it isfalse
so your condition in your middleware isif (false == '1')
so it always fails the condition. You should try to remove the!
at the start of the condition and change it toAuth::user()->roll_as !== '1'
Because the ! operator has a higher precedence than the == operator, the ! operator will happen first. Reference more https://www.php.net/manual/en/language.operators.precedence.php
You can do:
// you can use 1 instead of ‘1’
Or:
// you can use 1 instead of ‘1’
Or if Auth::user()->roll_as is an integer type, you can use:
if Auth::user()->roll_as is a string type, it should be:
Reference https://www.php.net/manual/en/language.operators.comparison.php