Do not redirect if guest?

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?


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,
    ...
];