Back

Can't use private access on Eloquent's local scope


ishibashi takken posted 4 months ago

I'm japanese student and new to Laravel.

I used the Eloquent's local scope like this:

use Illuminate\Database\Eloquent\Model;
class Test extends Model {
    public static function scopeSample($query) {
        return $query->where('name');
    }
}

For reasons of the security, I changed access-modifier into private:

use Illuminate\Database\Eloquent\Model;
class Test extends Model {
    private static function scopeSample($query) {
        return $query->where('name');
    }
}

And I had exception:

(1/1) BadMethodCallException
Call to undefined method App\Entities\Domains\Test::sample()

Why I can't use local scope in private access? Please tell me the answer.

Tobias van Beek replied 4 months ago

I don't understand the reason that you want to add the scope functions as private. The scope is used to create a query, that will be done from outside of the class so that shouldn't be private.

Also the function shouldn't be static, see https://laravel.com/docs/5.6/eloquent#local-scopes for more information.

ishibashi takken replied 4 months ago

Sorry, It is necessary to define some methods to access scopeSample...

use Illuminate\Database\Eloquent\Model;

class Test extends Model {

    private static function scopeSample($query) {

        return $query->where('name');
    }

    public static function getTable() {
        $table = self::sample()
        ->get();

        return $table;
    }

     public static function getTableCount() {
        $table = self::sample()
        ->get();

        if ($table->count() === 0) {
            return false;
        }
        else
        {
            return true;
        }
    }
}

Actually I want to share the scope with different public methods.
I'm sorry for confusing you.

Tobias van Beek replied 4 months ago

Because of the working of eloquent it isn't possible to set the scope functions on private.


Sign in to participate in this thread!



We'd like to thank these amazing companies for supporting us