Search code examples
laravellaravel-5laravel-authentication

Authentication redirect route


can you help me how to create if isadmin is true it will be redirected to admin page, else home page.

AuthController

public function postLogin(Request $request){
       if(!auth()->attempt(['email' => $request->email, 'password' => $request->password])){
        return redirect()->back();
       }
       return redirect()->route('home');
    }

the main reason's maybe because this

return redirect()->route('home');

when tried change to ('admin') it successfully redirecting.

when i tried to add

protected function authenticated(\Illuminate\Http\Request $request, $user)
    {
        if( $user->isadmin){
           return redirect('admin');
        }
        return redirect('home');
    }

it didnt works too


Solution

  • I suggest creating a middleware and using it to protect the route

    Example, you can create an Admin middleware

    php artisan make:middleware Admin
    

    In App\Http\Middleware\Admin.php

    use Auth;
    use Session;
    use Closure;
    
    public function handle($request, Closure $next)
        {
            // Check if user has permission to access route
            if(!Auth::user()->admin) {
                Session::flash('info', 'You do not have permission to perform this operation!');
    
                return redirect()->back();
            }
    
            return $next($request);
        }
    
    

    Then in the protected route(assuming only your admin can view all posts in this route),

    Route::post('admin/post/index', 'PostController@index')->middleware('auth');
    
    

    Or in the controller

    public function __construct()
    {
         $this->middleware('auth');
     }
    
    

    Use except to exclude routes or only to include methods.

    In the kernel.php

    protected $routeMiddleware = [
         ...
         'admin' => \App\Http\Middleware\Admin::class
    ];