条件 return 模型 Laravel

Conditionally return Model Laravel

我对 Laravel、

很陌生

我想知道我们如何在模型上应用一些条件。

假设有一个字段is_public如果这个字段是false 这样只有管理员才能看到这些数据..

我不想在带有 where 子句的控制器上执行此操作,因为将来我可能会在很多地方使用模型,还有关系..

我认为一个好的解决方案是政策:https://laravel.com/docs/8.x/authorization#creating-policies

Policies are classes that organize authorization logic around a particular model or resource. For example, if your application is a blog, you may have a App\Models\Post model and a corresponding App\Policies\PostPolicy to authorize user actions such as creating or updating posts.

您可以像这样为您的模型创建策略:

php artisan make:policy YourModelPolicy --model=YourModel

那么视图方法可能是这样的:

public function view(User $user, YourModel $model)
{
    if ($user->isAdmin()) return true;

    if ($model->is_public) return true;

    return false;
}

我想 Laravel Global Query Scope 就是您要找的。

Global scopes allow you to add constraints to all queries for a given model. Laravel's own soft delete functionality utilizes global scopes to only retrieve "non-deleted" models from the database. Writing your own global scopes can provide a convenient, easy way to make sure every query for a given model receives certain constraints.

基本上,它可以全局应用任何子句。

我们可以做的是,在我们的Model上定义一个GLobal Query Scope, 所以每次调用我们的模型时,我们都可以检查用户是否不是管理员或没有权限查看私人数据的人,然后使用 where('is_public', true).

这样的 where 子句扩展我们的查询

这是一个例子

App\Models\YourModel

   namespace App\Models;

   use Illuminate\Database\Eloquent\Model;
   use Illuminate\Database\Eloquent\Builder; // Dont forget to include

    protected static function booted()
    {
        static::addGlobalScope('visible', function (Builder $builder) {
            if (!optional(auth()->user())->can('The Permission Name')) {
                $builder->where('is_public', true);
            }
        });
    }

您可以使用查询范围做更多的事情,比如假设您不希望在您可以做的地方使用这个全局范围:

YourModel::withoutGlobalScope('visible')->get();

了解更多关于Query Scopes https://laravel.com/docs/8.x/eloquent#query-scopes