【问题标题】:How can I let user do CRUD only on the record created by him/ Her in Voyager Laravel?如何让用户仅对他/她在 Voyager Laravel 中创建的记录执行 CRUD?
【发布时间】:2018-11-01 14:10:30
【问题描述】:

我是 laravel 和 voyager 的新手

我有一个关于 voyager 的问题。问题是 .. 我想让用户只对他/她创建的记录执行 CRUD,因此他/她将无法访问其他用户的记录,但只能对他/她的记录执行添加-编辑-删除。如何在 voyager 中存档?默认权限适用于所有记录,不会过滤用户特定记录:(

【问题讨论】:

  • 我从未使用过 Voyager,但基本的想法是每个人都有一个 created_by(或等效的,例如 creatoruser_idowner_id 等)通过关系表/模型和过滤器(Model::where("created_by", "=", $user->id)->get()$user->model->get();)这个问题有点宽泛。尝试实现某些东西,如果您有特定问题,请发布另一个问题。

标签: laravel voyager


【解决方案1】:

Landlord 应该可以完美地解决这个问题。

Landlord 将为 Eloquent 应用一个全局范围,自动过滤记录。它在堆栈中的级别低于 Voyager,这意味着您不需要在 Voyager 端进行任何额外配置。

使用 Landlord,您只需在所有 CRUD 表中添加一列来标识记录的所有权,然后让 Landlord 知道这一点。

例如,如果您使用列名user_id,则可以通过像Landlord::addTenant('user_id', $userIdHere); 一样简单的调用将范围限定到任何地方的用户(比如在您的中间件中)这是一个示例中间件:

<?php
namespace App\Http\Middleware;
use Closure;
use App\User;
use Landlord as LandlordManager;

class Landlord {
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if ($request->user()) {
            LandlordManager::addTenant($request->user());
            LandlordManager::applyTenantScopesToDeferredModels();
        }
    }
}

然后转到App/Http/Kernel.php,找到$routeMiddleware 数组并添加:

'landlord' => \App\Http\Middleware\Landlord::class

然后转到app/routes/web.php 并根据您在文档https://laravel.com/docs/master/middleware 中最喜欢的风格将此中间件应用于任何单个路由或路由组。一个例子是:

Route::group(['prefix' => 'admin', 'middleware'=>'landlord'], function () {
    // routes here
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-18
    • 1970-01-01
    • 2017-09-22
    • 1970-01-01
    • 2016-01-19
    • 2019-11-13
    • 2022-01-26
    • 2018-07-22
    相关资源
    最近更新 更多