如何在 CRUD 之前检查用户是否拥有资源

我正在尝试清理我的控制器操作,但我不确定如何最好地进行。我有一个编辑操作,我通过路由模型绑定接收资源。我想在修改之前检查用户是否拥有此资源,如果没有,则重定向到通用索引路由


public function show(Document $document)

{

    //  This works fine, but I've repeated this for all other 

    //  actions where user views or modifies resource. How do

    //  I share this functionality with view/show/delete?

    if ($document->user_id !== Auth::id()) {

        return redirect('documents');

    }


    return view('documents.show', compact('document'));

}

如何在不为每个操作(例如显示/编辑/查看)重复这些行的情况下实现此行为?谢谢!


临摹微笑
浏览 135回答 1
1回答

浮云间

您可以制作一个中间件来检查经过身份验证的用户 id 是否等于方法$request->document->user_id中的handle,并在控制器的构造方法中应用中间件(显示、查看、删除)这是一个示例实现php artisan make:middleware DocumentsOwnerShip<?phpnamespace App\Http\Middleware;use Closure;class DocumentsOwnerShip{&nbsp; &nbsp; public function handle($request, Closure $next)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; if ($request->document->user_id !== auth()->id()) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return redirect('documents');&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return $next($request);&nbsp; &nbsp; }}在你的控制器中<?phpnamespace App\Http\Controllers;use Illuminate\Http\Request;use App\Http\Middleware\DocumentsOwnerShip;class DocumentsController extends Controller{&nbsp; &nbsp; public function __construct()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; $this->middleware(DocumentsOwnerShip::class)->only(['view', 'show', 'delete']);&nbsp; &nbsp; }&nbsp; &nbsp; public function show(Document $document)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return view('documents.show', compact('document'));&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP