php - Laravel login redirect issue based on role of user: redirect too many times
Get the solution ↓↓↓I am trying to make code in Laravel using middleware which will redirect user depending on user's role. The issue is I get error: redirected too many times whether user is simple user or admin. I am so far performing check whether user is admin by providing string in middleware, i am not accessing db yet. Any help is greatly appreciated.
Here is my code below:
mid.php (Middleware)
class mid
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if($request->session()->has('user')){
$user = $request->session()->get('user');
if($user == "[email protected]"){
return redirect()->route('adminview');
}else{
return redirect()->route('userview');
}
}else{
return redirect()->route('login')->with('poruka','Niste administrator!');
}
return $next($request);
}
}
Web.php
<?php
/*
|
LoginController.php
{-code-3}
Answer
Answer
Solution:
Your middleware will redirect a user who isn't"[email protected]"
to theuserview
route. You have this middleware assigned to theuserview
route.
So if there is a user in the session and they are not"[email protected]"
they will get into an endless loop being redirected to the same route, then the middleware will redirect them to the same route again, in a loop.
This is also an issue for when you have this assigned to theadminview
. If you are the "admin" and you try to hit that route, you will also end up in an endless loop.
In short you are telling it to redirect endlessly.
This middleware will never let anyone get to the destination route. It can only redirect to somewhere else.
Update:
Here is a rough idea of what you could do for an Admin check middleware
Admin Middleware:
public function handle($request, $next)
{
// an auth middleware could handle this itself
if (! ($email = $request->session()->get('user'))) {
// not logged in at all
return redirect()->route('login');
}
if ($email != '[email protected]') {
// not the admin user
// redirect them away
return redirect()->route(...);
}
// let the request pass through as we have determined they are the admin
return $next($request);
}
This middleware would get assigned to a route that you only want the admin to be able to access.
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: using $this when not in object context
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.