How to control routes using laravel middleware?

0

I have a system with the following routes

  • '\'
  • 'expenses'
  • '\ register'
  • '\ login'
  • 'home'
  • of these routes would like to leave only unauthenticated user '\' and '\ login',

    For this I changed the handle function of the RedirectIfAuthenticated class, so that when it is authenticated it is directed to home, otherwise go to the login page. This worked for register, but when access \ expenses I get access even though it is not authenticated.

    public function handle($request, Closure $next, $guard = null)
    {
        if (!$request->is('login') && Auth::guard($guard)) {
            return redirect('/home');
        }
    
        return $next($request);
    }
    
        
    asked by anonymous 19.12.2017 / 19:20

    1 answer

    0

    You can reach your middleware if the user is logged in:

    /**
         * Handle an incoming request.
         *
         * @param  \Illuminate\Http\Request  $request
         * @param  \Closure  $next
         * @return mixed
         */
        public function handle($request, Closure $next)
        {
    
            if (!Auth::check()) {
                return redirect('/login');
            }
    
            return $next($request);
        }
    

    And in your route file group the routes that you want to be authenticated within this Middleware:

     Route::group(['middleware' => 'auth_site'], function () {
        Route::get('despesas', ['uses' => 'DespesasController@index', 'as' => 'despesas']);
       [...]
     });
    
        
    19.12.2017 / 19:25