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

JoaoHamerski's avatar

How to perform a query search of all "clients" from a Builder instance of "products"

So, i have a Builder instance of "products" with Product::orderBy('purchase_date', 'desc') , and each of my products have a 'client_id' field, now i just want to get all products where the client name is like something, how can i do it?

That is the (ugly) way i implemented it, is this correct or there is a better way to do it?


// Here i get all products
$products = Product::orderBy('purchase_date', 'desc');

// Here i get all id of the clients, remove duplicates with "unique" and sort.
$clients = $products->pluck('client_id')->unique()->sort();

// Now i find all clients passing a array of IDs
$clients = Client::find($clients);

// Here i create a new collection of Clients
$clients = (new Client)->fill($clients->toArray()); 

// The method getBySearch basically return a query search 
// like this: $clients->where($table, 'like', '%' . $query['search'] . '%');
// where i get all clients that matches the search
$clients = $this->getBySearch($request->query(), $clients);

// Now i return all products with the client ids
 $products = Product::where('client_id', $clients->pluck('id'));
       

So, this code gives me all products of a client that have, for example, 'Lu' in his name. There is a better way to do that?

0 likes
2 replies
Snapey's avatar
Snapey
Best Answer
Level 122

Why do you need to start with a product?

$clients = Client::with('products')->where('name', 'like', "%{$query['search']}%")->get()

if you want just the products of matching clients

$products = Product::whereHas('client',function($q) use($query){
		$q->where('name', 'like', "%{$query['search']}%");
	})->get();
JoaoHamerski's avatar

@snapey I just noticed it now, i don't need to start with product, i didn't know how whereHas was used, thanks, your solution works perfectly.

Please or to participate in this conversation.