phplaravellaravel-5laravel-5.7global-scope

Register New Global Scope in Laravel


I want to register a new global scope in Laravel 5.7 but I got the following error:

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());
        });
    }
}

I'm using laravel 5.7 PHP 7.2


Solution

  • You are trying to add an anonymous global scope which is absolutely fine but you need to use Eloquent\Builder for that approach to work (this doesn't seem to fit your exact error, however, you will need this) so add the following to your class and see if the error changes!!

    use Illuminate\Database\Eloquent\Builder;