0
votes

I used a middleware to check users. here i have two users admin and student. both details are stored in user table.Now the problem is when i go for login it redirects to admin dashboard page but the page is shown not to working, redirects too many times. Middleware

public function handle($request, Closure $next)
    {
        if(Auth::User()->type == 1) {
            return redirect('AdminDashboard');
        } else {
            redirect('StudentDashboard');
        } 
    }

homeController

use App\Http\Middleware\checkUser;
public function __construct()
    {
        $this->middleware('auth');
        $this->middleware('checkUser');

    }
    public function index()
    {
        if(!(Auth::User)){
            return redirect('login');
        }

    }

web.php

Auth::routes();
Route::get('/','UserController@index');
Route::get('/home', 'HomeController@index')->name('home');
Route::get('AdminDashboard', 'DashboardController@index')->name('AdminDashboard');
Route::get('dashboard/videos', 'DashboardController@videos')->name('adminVideos');
Route::post('file-upload/upload', 'FileUploadController@upload')->name('upload');
Route::get('StudentDashboard', 'DashboardController@studentRegister')->name('StudentDashboard');
Route::post('/newRegister', 'UserController@newRegister')->name('newRegister');

DashboardController

use App\Http\Middleware\checkUser;
public function __construct()
    {
        $this->middleware('auth');
        $this->middleware('checkUser');
    }

    public function index()
    {
        $students = Students::with('classes')->with('subclasses')->get();
        return view('admin.dashboard',compact('students'));
    }
public function studentRegister()
    {
        $classes = Classes::where('status', '1')->get();
        $subclasses = SubClass::where('status', '1')->get();
        return view('admin.studentRegister',compact('classes','subclasses')); 
    }

After login

2
try this in your middleware return redirect('StudentDashboard'); Reza sh
return redirect('StudentDashboard'); useA.A Noman
You should be added to check user functionality in your controller. Because when middleware redirect to admin dashboard then it's called again that's why it redirects to multi-timeMr Perfect

2 Answers

0
votes

You should be added to check user functionality in your controller. Because when middleware redirects to the admin dashboard then it's called again that's why it redirects to multi-time. If you want to use middleware still yet then return view in middleware. Hopefully, it will be helpful for you.

0
votes

When you redirect, then it comes back to the same middleware and redirects again & again which leads to multiple redirects. So, instead of redirect in both cases, use return $next in the right case and redirect in the wrong case. eq:

public function handle($request, Closure $next)
    {
        if(Auth::User()->type == 1) {
            return $next;
        } 
        redirect('StudentDashboard');
    }