【发布时间】:2020-11-12 23:36:01
【问题描述】:
我有一个NotificationPolicy,代码如下:
<?php
namespace App\Policies;
use App\Notification;
use App\User;
use Illuminate\Auth\Access\HandlesAuthorization;
class NotificationPolicy
{
use HandlesAuthorization;
public function update(User $user, Notification $notification)
{
return $user->id === $notification->user_id;
}
}
我已通过将其添加到AuthServiceProvider 来正确注册:
protected $policies = [
Notification::class => NotificationPolicy::class,
];
我这样做是为了只有登录的用户才能通过将archived_at 值或read_at 值设置为当前时间戳等操作来更新他们的通知。如果我在控制器中使用它,该策略确实有效,即;
class ArchiveItemController extends Controller
{
public function __invoke(Notification $notification)
{
$this->authorize('update', $notification);
$notification->markAsArchived();
return redirect()->route('inbox.index')->with('success', 'Item has been archived');
}
}
但是我不想在控制器中使用它们,而是希望在我的路由文件中使用它们。所以我从控制器中删除了这一行$this->authorize('update', $notification);,我尝试了以下方法,但它不起作用:
Route::prefix('inbox')->middleware(['auth', 'can:employee'])->group(function () {
Route::get('/notification/{notification}/archive', 'User\Account\Inbox\ArchiveItemController')
->name('inbox.item.archive')
->middleware('can:update', 'notification');
});
我什至运行了以下命令,但它们没有任何区别:
php artisan optimize
php artisan cache:clear
php artisan route:cache
php artisan view:clear
php artisan config:cache
【问题讨论】:
-
根据docs 应该是:
->middleware('can:update,notification') -
非常感谢 Remul。我犯了一个错误,因为我有
->middleware('can:update', 'notification')当你正确地说它应该是->middleware('can:update,notification')- 我必须运行以下命令才能使更改生效:php artisan cache:clear && php artisan config:clear && php artisan route:clear && php artisan view:clear && php artisan clear-compiled && composer dumpautoload
标签: laravel routes authorization middleware policy