Skip to content
Advertisement

Laravel where on relationship object

I’m developing a web API with Laravel 5.0 but I’m not sure about a specific query I’m trying to build.

My classes are as follows:

JavaScript

and

JavaScript

Now, I want to get all the events with a specific participant. I tried with:

JavaScript

but the where condition is applied on the Event and not on its Participants. The following gives me an exception:

JavaScript

I know that I can write this:

JavaScript

but it doesn’t seem very efficient to send so many queries to the server.

What is the best way to perform a where through a model relationship using Laravel 5 and Eloquent?

Advertisement

Answer

The correct syntax to do this on your relations is:

JavaScript

This will return Events where Participants have a user ID of 1. If the Participant doesn’t have a user ID of 1, the Event will NOT be returned.

Read more at https://laravel.com/docs/5.8/eloquent-relationships#eager-loading

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement