Using Laravel 12, I have a custom routes file.
All the routes in this file should be blocked to guests and users that don't have a specific permission.
I can't make the middlware work correctly.
The user I am testing has the permission 'admin dashboard' through the 'admin' role.
The routes file: routes/admin.php:
use Illuminate\Support\Facades\Route;
Route::get('/dashboard', function () {
dd('admin');
})->name('dashboard');
In bootstrap/app.php:
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__ . '/../routes/web.php',
commands: __DIR__ . '/../routes/console.php',
health: '/up',
then: function () {
Route::middleware( 'admin')
->prefix('admin')
->name('admin.')
->group(base_path('routes/admin.php'));
},
)
->withMiddleware(function (Middleware $middleware): void {
//
$middleware->append(ProtectAgainstSpam::class);
})
->withExceptions(function (Exceptions $exceptions): void {
//
})->create();
In App/Http/Middleware/AdminMiddleware:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use Illuminate\Support\Facades\Auth;
class AdminMiddlware
{
/**
* Handle an incoming request.
*
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
*/
public function handle(Request $request, Closure $next): Response
{
//Tried
if (! $request->user() || ! $request->user()->can('admin dashboard')) {
//And Tried
if (! Auth::user() || ! Auth::user()->can('admin dashboard')) {
abort(403, 'Unauthorized action.'); // Or redirect to a different page
}
return $next($request);
}
}
Even though the user is logged in and has the permission, I get the Unauthorized page.
using: dd(Auth::user()) or dd($request->user()) both return null.
Can anyone help please?