在Laravel注册新的全球范围



我想在Laravel 5.7中注册一个新的全局作用域,但我得到了以下错误:

Symfony\Component\Debug\Exception\FatalThrowableError(E_PARSE(语法错误,意外的"static"(T_static(

<?php
namespace App;
use Auth;
use IlluminateDatabaseEloquentModel;
use IlluminateDatabaseEloquentSoftDeletes;
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

您正在尝试添加一个匿名全局作用域,这是完全可以的,但您需要使用Eloquent\Builder才能使用这种方法(这似乎不适合您的确切错误,但是,您需要这样做(,所以将以下内容添加到您的类中,看看错误是否发生了变化!!

use IlluminateDatabaseEloquentBuilder;

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

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

使用此包生成全局作用域并将其加载到laravel 中

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

php artisan make:scope UserScope

php artisan make:scope ActiveScope

php artisan make:scope AgeScope

等等。。。

最新更新