Laravel Eloquent Retrieving Only Certain Rows Basing On Relation Field

- 1 answer

I have a number of models and I have the relationships set up correctly I believe.

I want to retrieve all of the models from a table if and only if the active column of a foreign key table is true.

I have tried a number of variations but to no avail.

Below is the set up.

The table is question is called device, which points to a table called dep.

The DEVICE model has the following relationship to DEP

public function dep() {

    return $this->belongsTo('App\Dep');


The DEP model has a column called active, which is set to true or false.

What eloquent command should I use to return all Devices where the active field of the DEP table is true?

At the moment I am having to get all the DEP models and then only get the devices if the active field is set to true but I am sure there must be a more elegant approach.




If you want to limit the results based on the existence of a field in a related model, you want to take a look at the whereHas method.

$devices = Device::whereHas('dep', function($query) {
    $query->where('active', '=', true); // Replace true with 1 if you aren't using casts

This will get all devices that have a dep with the active field of true. This will not fetch dep along with the Device though. If you want that, then just use whereHas with eager loading as you normally would do like this:

$devices = Device::with('dep')->whereHas('dep', function($query) {
    $query->where('active', '=', true);