我有一条销毁帖子的路线,我该如何做才能使能够访问路线的人仅是帖子创建者?例如,我有一个ID为3的帖子,用户ID为5,所以唯一可以删除3的帖子只有用户ID5。我曾尝试与中间件打交道,但还不够幸运,无法使其正常工作。
CekStatus.php(中间件)
class CekStatus
{
public function handle($request, Closure $next)
{
$userId = $request->id;
$user = Post::where('id', $userId)->select('user_id')->pluck('user_id')->first();
if ($user === Auth::id()) {
return $next($request);
}
return redirect('/'); //redirect anyware.
}
}
路线
Route::get('/hapus/{id}','PostController@destroy')->middleware('cekstatus');
Kernel.php
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
'cekstatus' => \App\Http\Middleware\CekStatus::class,
],
'api' => [
'throttle:60,1',
'bindings',
],
];
输出:
ERR_TOO_MANY_REDIRECTS
答案 0 :(得分:1)
您应该在此处使用Policy,该中间件不用于授权目的。 here文档中对此有更多介绍。
文档也使用您的示例,而不是更新,您可以创建一个delete函数,然后在您的控制器中使用它,您可以添加以下内容:
if (auth()->user()->can('delete', $post)) {
// delete it code here.
}