Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if belongsToMany relation exists - Laravel

Two of my tables (clients and products) have a ManyToMany relation using Laravel's blongToMany and a pivot table. Now I want to check if a certain client has a certain product.

I could create a model to check in the pivot table but since Laravel does not require this model for the belongsToMany method I was wondering if there is another way to check if a certain relationship exists without having a model for the pivot table.

like image 631
almo Avatar asked Jul 03 '14 13:07

almo


2 Answers

I think the official way to do this is to do:

$client = Client::find(1); $exists = $client->products->contains($product_id); 

It's somewhat wasteful in that it'll do the SELECT query, get all results into a Collection and then finally do a foreach over the Collection to find a model with the ID you pass in. However, it doesn't require modelling the pivot table.

If you don't like the wastefulness of that, you could do it yourself in SQL/Query Builder, which also wouldn't require modelling the table (nor would it require getting the Client model if you don't already have it for other purposes:

$exists = DB::table('client_product')     ->whereClientId($client_id)     ->whereProductId($product_id)     ->count() > 0; 
like image 74
alexrussell Avatar answered Sep 29 '22 10:09

alexrussell


The question is quite old but this may help others looking for a solution:

$client = Client::find(1); $exists = $client->products()->where('products.id', $productId)->exists(); 

No "wastefulness" as in @alexrussell's solution and the query is more efficient, too.

like image 41
Mouagip Avatar answered Sep 29 '22 10:09

Mouagip