'How to shorten this eloquent command
I have used this Eloquent command to get some data from the database table:
$categories = Category::where('category_type',2)->orWhere('category_type',3)->orWhere('category_type',4)->get();
return view('admin.categories.index', compact('categories'));
So I want category_type of 2,3 and 4 but I wanted to shorten this command, so I tried this instead:
$categories = Category::where('category_type',[2,3,4,5])->get();
But it does not work properly and only show data with category_type of 2!
So the question is how can I shorten these orWhere commands? Is there any way for doing that?
Solution 1:[1]
This might be an overkill, but turn your glare into:https://github.com/rinvex/laravel-categories.
It's quite hard at the beginning, but gives lots of stuff instead.
Remember that in laravel you can go local/global scope inside your model https://laravel.com/docs/8.x/eloquent#query-scopes
public function scopePopular($query)
{
return $query->where('votes', '>', 100);
}
You can chain queries this way. The sample is from docs. Don't even think about 'repository pattern'. In my opinion it violates the above functionality and makes your code a bunch of mess. Just play around and make your queries inside model.
When you find yourself in hard situation, when you need to create something from few models involved (model aggregation), you might think about services/helpers/WHATEVER. The same role is given to view models in MVVM, as they prepare data for controller.
These are heavy logic classes, which make most of your work behind and they are called by controller/command-line/anything.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Elboyler |
