Skip to content

Instantly share code, notes, and snippets.

@blood72
Created June 29, 2020 07:11
Show Gist options
  • Save blood72/7e456f5445a789fa7167e0bd79de3f8e to your computer and use it in GitHub Desktop.
Save blood72/7e456f5445a789fa7167e0bd79de3f8e to your computer and use it in GitHub Desktop.
404 middleware version of spatie/laravel-permission.
<?php
namespace App\Http\Middleware;
use Closure;
use Spatie\Permission\Middlewares\PermissionMiddleware as Middleware;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class Permission404Middleware extends Middleware
{
/**
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param mixed $permission
* @return mixed
* @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
*/
public function handle($request, Closure $next, $permission)
{
try {
return parent::handle($request, $next, $permission);
} catch (\Spatie\Permission\Exceptions\UnauthorizedException $exception) {
throw new NotFoundHttpException();
}
}
}
@blood72
Copy link
Author

blood72 commented Jun 29, 2020

Example

in app/Http/Kernel.php

<?php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    // ...

    protected $routeMiddleware = [
        // ...
        'permission' => \Spatie\Permission\Middlewares\PermissionMiddleware::class,
        'permission.404' => \App\Http\Middleware\Permission404Middleware::class,
    ];

    // ...
}

in routes/web.php

Route::prefix('/admin')->middleware('permission.404:show admin page')->group(function () {
    Route::get('/', function () {
        return view('admin.dashboard');
    });

    // ...
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment