0

Is there a way to use guest middleware yet, if the request->expectsJson() it does not redirect, just errors? (Like the auth middleware).

Or would I need to write custom middleware?

panthro
  • 22,779
  • 66
  • 183
  • 324
  • What do you want to do exactly? Redirect a user when they're not logged in? – D1__1 Jan 17 '22 at 09:52
  • I do not want to redirect a user if logged in, if they are logged in I want to return an unauthorised error. – panthro Jan 17 '22 at 09:54
  • I assume you mean that you want to return an unauthorised error when the user **is not** logged in right? If not, please try to elaborate because it's a little confusing. – D1__1 Jan 17 '22 at 10:07
  • User in unauthroised if they are logged in e.g. allow guests but not authed users. – panthro Jan 17 '22 at 10:15

1 Answers1

1

You can make your own middleware inspired by RedirectIfAuthenticated:

app/Http/Middleware/AbortIfAuthenticated.php

<?php

namespace App\Http\Middleware;


use App\Providers\RouteServiceProvider;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class AbortIfAuthenticated
{

    public function handle(Request $request, Closure $next, ...$guards)
    {
        $guards = empty($guards) ? [null] : $guards;

        foreach ($guards as $guard) {
            if (Auth::guard($guard)->check()) {
                abort(403, "Not allowed");
            }
        }

        return $next($request);
    }
}

Then replace the middleware by your own in app/Http/Kernel.php (Or add a new one)

protected $routeMiddleware = [
    ...
    'guest' => \App\Http\Middleware\AbortIfAuthenticated::class,
    ...
];

Clément Baconnier
  • 5,718
  • 5
  • 29
  • 55