1

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.

1
  • if all() is an issue, you can always use query() Commented Jan 10, 2022 at 2:34

1 Answer 1

2

$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.

Sign up to request clarification or add additional context in comments.

1 Comment

When i use $this->categories()->CalculateMaxPositionSelectedCategory()->get(); get error Method App\Http\Livewire\FormStorCategory::categories does not exist. it's a little closer but still doesn't work

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.