How to control routes using Arable middleware?

Asked

Viewed 948 times

0

I have a system with the following routes

  1. '\'
  2. '\expenses'
  3. '\Register'
  4. '\login'
  5. '\home'

of these routes would like to make available only for user NOT authenticated ' ' 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 login page. This worked for Registry, but when accessing expenses I can access even if I am not authenticated.

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

    return $next($request);
}

1 answer

1

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 archive group the routes you want authenticated within that Middleware:

 Route::group(['middleware' => 'auth_site'], function () {
    Route::get('despesas', ['uses' => 'DespesasController@index', 'as' => 'despesas']);
   [...]
 });
  • Can’t I do the opposite? group the routes do not want authenticate, otherwise authenticate the others, or I have to spectrify only the routes that need authentication?

  • You can also, there just make the opposite condition of what I put in the middleware in the answer above, ai creates as guest and groups these routes in this Middleware

Browser other questions tagged

You are not signed in. Login or sign up in order to post.