Łukasz Okaj
Łukasz Okaj

Reputation: 11

Laravel scope method error when call on variable

I have a method scoup scopeCalculateMaxPositionSelectedCategory in my Model Category

class Category extends Model
{
    use HasFactory;

    protected $fillable = [
        'parent_id',
        'name',
        'slug',
        'description',
        'position',
        'quantity_available_offers',
    ];

    public function scopeCalculateMaxPositionSelectedCategory($query, $cat_id = null) {
        return $query->where('parent_id', $cat_id)->max('position');
    }
}

When i call like that it's work fine:

 Category::CalculateMaxPositionSelectedCategory();

But i want do this that way:

$this->categories->CalculateMaxPositionSelectedCategory();

After this are error: "BadMethodCallException Method Illuminate\Database\Eloquent\Collection::CalculateMaxPositionSelectedCategory does not exist. "

Show me why I want to do that, because i want to use this in component Livewire:

    public $selCategory = '';
    public $categories;
    public $selPosition;

    public function render()
    {
        $this->categories = Category::all();
        $this->selPosition = $this->categories->CalculateMaxPositionSelectedCategory() + 1;

        return view('livewire.form-stor-category');
    }

It supposes the error is due to all () calling get (). But I have no idea how to solve it.

Upvotes: 1

Views: 459

Answers (1)

Eden Dowling-Mitchell
Eden Dowling-Mitchell

Reputation: 271

$this->categories->CalculateMaxPositionSelectedCategory();

^ This line gets the categories as a collection, and then you can't call a query scope on a collection.

Try this:

$this->categories()->CalculateMaxPositionSelectedCategory()->get();

The () after categories will continue building the query but won't run it yet. When you call $this->categories without the () it runs the query straight away and your opportunity to use the scope is gone.

Upvotes: 2

Related Questions