kodfire
kodfire

Reputation: 1783

Laravel - Middleware for route always 403

App\Http\Controllers\Admin\ExampleController.php

public function index()
{
    dd('index');
}

app\Policies\ExamplePolicy.php

public function viewAny(User $user)
{
    return true;
}

app\Providers\AuthServiceProvider.php

protected $policies = [
    'App\Models\Example' => 'App\Policies\ExamplePolicy',
];

routes/admin.php

Route::get('example', [ExampleController::class, 'index'])->middleware('can:viewAny,App\Models\Example')

But the ->middleware('can:viewAny,App\Models\Example') always returns 403, and when I remove it, the dd('index') will run.

Have I missed something?

Upvotes: 1

Views: 539

Answers (1)

kodfire
kodfire

Reputation: 1783

Although I have logged in, the auth()->user() has been null due to the separation of the admin and others. So just by adding web to the middleware, it worked.

Route::get('example', [ExampleController::class, 'index'])->middleware(['web', 'can:viewAny,App\Models\Example'])

Upvotes: 1

Related Questions