Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

bobby_by's avatar

How to write search query with multiple conditions but where records under the same user

I have a database with inventory products. Also, I have many users where products belonged to different users. So I need to write a query with multiple conditions, where search needs to be in different table columns, so it will be a couple of ->orWhere() statements. But the search needs to find all the products that belonged to the same user. But if I have many ->orWhere() conditions, query starts searching the products under other users where other queries conditions match ("title" or "product_number").

So how can I change my code, where I can get all products with search keyword where the products under the same user?

Here is my code:


public function searchProduct(Request $search){
        $search_item = $search->search;
        $user = User::where('id', Auth::user()->id)->first();
        $inventory = Inventory::where('client_id', $user->client_id)
                                ->where('product_number', 'like', "%{$search_item}%")
                                ->orWhere('title', 'like', "%{$search_item}%")
                                ->orWhere('other_product_numbers', 'like', "%{$search_item}%")
                                ->with(['deliveryRecord', 'orderInRecord', 'sellRecord'])
                                ->paginate(50);

        $cleint_currency = SettingsClientCurrency::where('client_id', $user->client_id)->first();

        $inventory_products = Inventory::where('client_id', $user->client_id)->with('orderInRecord')->get();
        $inventory_total = 0;
        foreach ($inventory_products as $product) {
            $ordersin = $product->orderInRecord;
            foreach ($ordersin as $orderin) {
                $inventory_total += $orderin['price'] * $orderin['units'];

            }
        }

        return view('layouts.inventory.inventory')
                ->with('inventory', $inventory)
                ->with('inventory_total', $inventory_total)
                ->with('cleint_currency', $cleint_currency)
                ->with('user', $user);
    }
0 likes
3 replies
bobbybouwmann's avatar
Level 88

You can do something like this

$inventory = Inventory::where('client_id', $user->client_id)
    ->where(function ($query) {
        return $query->where('product_number', 'like', "%{$search_item}%")
            ->orWhere('title', 'like', "%{$search_item}%")
            ->orWhere('other_product_numbers', 'like', "%{$search_item}%");
    })
    ->with(['deliveryRecord', 'orderInRecord', 'sellRecord'])
    ->paginate(50);    

Not sure if this is a correct example in your case, but you get the idea ;)

Documentation: https://laravel.com/docs/6.x/queries#parameter-grouping

1 like

Please or to participate in this conversation.