3

I'm building a way to organize Items based on different requests:

$items = Item::query()
    ->where("type", $itemType)
    ->when($mode, function (Builder $query, $mode) {
        switch ($mode) {
            case "TopFavorites":
                return $query->orderByDesc('number_favorited');
            case "BestSelling":
                return $query->orderByDesc('number_sold');
            case "RecentlyUpdated":
                return $query->orderByDesc('updated_at');
            case "ForSale":
                return $query->where("onSale", true);
            case "Offsale":
                return $query->where("onSale", false);
        }
    })
    ->get();

I'm wondering if you can move the function in when to an external function in the controller class. I tried doing so however it seems the $query variable is not carried over even if you add it as an argument.

private function whenModeQuery(Builder $query, string $mode) {
    switch ($mode) {
        case "TopFavorites":
            return $query->orderByDesc('number_favorited');
        case "BestSelling":
            return $query->orderByDesc('number_sold');
        case "RecentlyUpdated":
            return $query->orderByDesc('updated_at');
        case "ForSale":
            return $query->where("onSale", true);
        case "Offsale":
            return $query->where("onSale", false);
    }
}
$items = Item::query()
    ->where("type", $itemType)
    ->when($mode, $this->whenModeQuery($query, $mode))
    ->get();

The code above gives me a Undefined variable $query error.

New contributor
ThePlayerRolo is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
1
  • 2
    That will invoke the function immediately. Try using $this->whenModeQuery(...) to pass the function reference Commented yesterday

2 Answers 2

1

As apokryfos pointed out in the comment, the issue is that you're calling the method immediately instead of passing it as a function reference to when(). The correct way is:

$items = Item::query()
    ->where("type", $itemType)
    ->when($mode, function (Builder $query, $mode) {
        return $this->whenModeQuery($query, $mode);
    })
    ->get();

Reference: https://laravel.com/docs/12.x/collections#method-when

Without any additional internal code, it can also be shortened:

$items = Item::query()
    ->where("type", $itemType)
    ->when($mode, fn (Builder $query) => $this->whenModeQuery($query, $mode))
    ->get();

Reference: How to use arrow functions in PHP?

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

1 Comment

->when($mode, fn (Builder $query) => $this->whenModeQuery($query, $mode)) - short version
1

If you want to move your whenModeQuery function into the Item model, you can do it using a scope. This way, you can access it from the $query variable through the Item scopes, like this:

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;

class Item extends Model
{
    protected function scopeWhenModeQuery(Builder $query, ?string $mode): Builder
    {
        if (!$mode) {
            return $query;
        }

        switch ($mode) {
            case "TopFavorites":
                return $query->orderByDesc('number_favorited');
            case "BestSelling":
                return $query->orderByDesc('number_sold');
            case "RecentlyUpdated":
                return $query->orderByDesc('updated_at');
            case "ForSale":
                return $query->where('onSale', true);
            case "Offsale":
                return $query->where('onSale', false);
            default:
                return $query;
        }
    }
}

From Laravel v12.40.0 onward, you can also use the Scope attribute:

use Illuminate\Database\Eloquent\Attributes\Scope;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;

class Item extends Model
{
    #[Scope]
    protected function whenModeQuery(Builder $query, ?string $mode): Builder
    {
        if (!$mode) {
            return $query;
        }

        switch ($mode) {
            case "TopFavorites":
                return $query->orderByDesc('number_favorited');
            case "BestSelling":
                return $query->orderByDesc('number_sold');
            case "RecentlyUpdated":
                return $query->orderByDesc('updated_at');
            case "ForSale":
                return $query->where('onSale', true);
            case "Offsale":
                return $query->where('onSale', false);
            default:
                return $query;
        }
    }
}

And in both cases, you use it from the $query in your query:

$items = Item::query()
    ->where('type', $itemType)
    ->when($mode, fn (Builder $query) => $query->whenModeQuery($mode))
    ->get();

Reference: https://laravel.com/docs/12.x/eloquent#query-scopes

Comments

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.