1
Product::where('name', 'like', 'something%')->orWhere('category', 'like', 'something%')->orWhere('price', 'like', 'something%')->orWhere('qty', 'like', 'something%')...

Can I do it in more elegant and compact way?

3 Answers 3

1

You can go about it this way. passing arrays to a single orWhere clause

Product::where('name', 'like', 'something%')->orWhere(['category', 'like', 'something%'], ['price', 'like', 'something%'],['qty', 'like', 'something%'])...

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

Comments

0

You can use the searchable, take a look here and here also here

Comments

0

You can use 'array_map()' to build an array for orWhere():

$search = 'something';
Product::orWhere(array_map(
    function ($i) use($search) { return [$i, 'like', $search.'%']; },
    ['name', 'category', 'price', 'qty']
))->get();

It's a good way if you have many fields to search by. For 3-4 fields, I'd just use simple orWhere() chaining, because it's easier to read the code

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.