I want to list all garages by car ID, but the way I still return information about garages, even if the car is not found, is the opposite, instead of not returning anything, the garages are returned using the car relationship is empty.
Let me give an example:
$garages = Garages::with(['cars'])->get();
This way I have everything and I can’t use ->where('car_id', 1)because the table garagedoes not have a column car_id. The only way I found was as follows:
$garages = Garages::with(['cars' => function($q) { return $q->where('car_id', 1); }])->get();
The problem is that even if the car is not found, the data from the garage is still being returned, and I do not want this because I want to use @forelsethe blade and, since it still returns data, it @emptynever works, and I get errors saying that I am trying to get properties from a non-object (of course, machines do not exist if they were not found).
Is there a way to use whereand return data only if it was found?
@edit - relationship
class Users extends Eloquent
{
public function cars()
{
return $this->hasMany('cars');
}
public function garages()
{
return $this->hasManyThrough('garages', 'cars', 'garage_id', 'garage_id');
}
}
class Garages extends Eloquent
{
public function cars()
{
return $this->hasMany('cars');
}
}
class Cars extends Eloquent
{
public function users()
{
return $this->belongsTo('users');
}
public function garages()
{
return $this->belongsTo('Garages');
}
}
yayuj source
share