在 Laravel 中注册新的全局范围

Register New Global Scope in Laravel

我想在 Laravel 5.7 中注册一个新的全局范围,但出现以下错误:

Symfony \ Component \ Debug \ Exception \ FatalThrowableError (E_PARSE) syntax error, unexpected 'static' (T_STATIC)

<?php

namespace App;

use Auth;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Order extends Model
{
    use SoftDeletes;

    /**
    * Anonymous scope
    */
    protected static function boot()
    {
        parent::boot();

        static::addGlobalScope('authenticated', function (Builder $builder) {
            $builder->where('id_user', '=', Auth::id());
        });
    }
}

我正在使用 laravel 5.7 PHP 7.2

5.7 中的全局作用域文档建议您应该以与此处不同的方式实现它们。 https://laravel.com/docs/5.7/eloquent#global-scopes.

您需要实现 Scope class 然后创建一个 apply() 方法。

您正在尝试添加一个匿名的全局范围,这绝对没问题,但您需要使用 Eloquent\Builder 才能使该方法起作用(这似乎不符合您的确切错误,但是,您将需要this) 所以将以下内容添加到您的 class 并查看错误是否更改!!

use Illuminate\Database\Eloquent\Builder;

使用此包生成全局范围并将其加载到 laravel

https://github.com/limewell/laravel-make-extender

php artisan make:scope UserScope

php artisan make:scope ActiveScope

php artisan make:scope AgeScope

等...