Bright boot using

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');
    }       
}
+4
source share
2 answers

I think you're wrong about that. If you need one car garages, why not find a car and get all the garages using relationships?

$user = User::find(1);
$garages = $user->garages;

foreach($garages as $garage){
    // just an example, you'll have to use your real properties
    echo 'Address: ' . $garage->address;
    echo 'Name: '. $user->name;
}
+2

.

$garages = Garages::with(['cars' => function($q) { $q->where('car_id', 1); }])
                    ->whereHas('cars', function($q) { $q->where('car_id', 1); })
                    ->get();

Update: .

$garages = Garages::has('cars')
                    ->with(['cars'])
                    ->get();
+2

All Articles