PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, February 20, 2022

[FIXED] Do not redirect if guest?

 February 20, 2022     laravel     No comments   

Issue

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?


Solution

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



Answered By - Clément Baconnier
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

1,205,335

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © 2025 PHPFixing