1

so 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.
2
  • 1
    That will invoke the function immediately. Try using $this->whenModeQuery(...) to pass the function reference Commented 2 hours ago
  • Oh that works, thank you! Commented 2 hours ago

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.