Laravel 9 sub-query target linked model columns in where clause

Viewed 17

I'm working inside a Laravel 9 project and am trying to perform a query and return my Monitor model where the User role of the monitor is a customer (eventually adding more fields).

My current query attempt throws an error:

Property [user] does not exist on the Eloquent builder instance.

What am I missing?

/**
 * Get inactive users
 *
 * @return array
 */
protected function getInactiveUsersWithMonitors()
{
    $monitors = Monitor::with('user')->where(function ($query) {
        $query->user->where('role', 'customer');
    })->get();

    return $monitors;
}
1 Answers

If you have already defined the user function in the Monitor model. Here is what you should do.

/**
 * Get inactive users
 *
 * @return array
 */
protected function getInactiveUsersWithMonitors()
{
    /* $monitors = Monitor::with('user')->where(function ($query) {
        $query->user->where('role', 'customer');
    })->get(); */

     $monitors = Monitor::whereHas('user', function($query)
{
    $query->where('role', 'customer');

})->get();
    

    return $monitors;
}

This will get all the details from the monitors table as well as the corresponding details from users table.

Related