Tuesday, February 8, 2022

[FIXED] How to shorten this eloquent command

Issue

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

Try whereIn()...

<?php

$categories = Category::whereIn('category_type',[2,3,4])->get();

return view('admin.categories.index', compact('categories'));

https://laravel.com/docs/8.x/queries#additional-where-clauses



Answered By - Simon K

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.