亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在 CRUD 之前檢查用戶是否擁有資源

如何在 CRUD 之前檢查用戶是否擁有資源

PHP
臨摹微笑 2022-01-24 10:50:11
我正在嘗試清理我的控制器操作,但我不確定如何最好地進行。我有一個編輯操作,我通過路由模型綁定接收資源。我想在修改之前檢查用戶是否擁有此資源,如果沒有,則重定向到通用索引路由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'));}如何在不為每個操作(例如顯示/編輯/查看)重復這些行的情況下實現此行為?謝謝!
查看完整描述

1 回答

?
浮云間

TA貢獻1829條經驗 獲得超4個贊

您可以制作一個中間件來檢查經過身份驗證的用戶 id 是否等于方法$request->document->user_id中的handle,并在控制器的構造方法中應用中間件(顯示、查看、刪除)


這是一個示例實現


php artisan make:middleware DocumentsOwnerShip

<?php


namespace App\Http\Middleware;


use Closure;


class DocumentsOwnerShip

{

    public function handle($request, Closure $next)

    {

        if ($request->document->user_id !== auth()->id()) {

            return redirect('documents');

        }

        return $next($request);

    }

}

在你的控制器中


<?php


namespace App\Http\Controllers;


use Illuminate\Http\Request;

use App\Http\Middleware\DocumentsOwnerShip;


class DocumentsController extends Controller

{

    public function __construct()

    {

        $this->middleware(DocumentsOwnerShip::class)->only(['view', 'show', 'delete']);

    }


    public function show(Document $document)

    {

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

    }

}


查看完整回答
反對 回復 2022-01-24
  • 1 回答
  • 0 關注
  • 156 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號