Lets say i have a model called 'manufacturer' and this model has one to many relation with another model 'vehicle'. Now i dont want to let users delete a manufacturer if there are any vehicles associated with this model.
//In Manufacturer model
public function vehicles()
{
return $this->hasMany('Vehicle');
}
And in the repository/controller i have another method to check for it.
public function checkAssociatedVehicles($id)
{
return Manufacturer::with('vehicles')->find($id)->toJson();
}
This does outputs the manufacturer data with all the associated vehicles. but this is not efficient, so i just want to check that if there is even one vehicle then dont delete the manufacturer.
I believe you'd want to use the has
method to make sure the manufacture has some vehicles.
$manufacture = Manufacturer::has('vehicles')->find($id);
Then you'd just want to make sure !is_null($manufacture)
As you have a vehicles()
method in your Manufacturer model, you may just do this:
Use the whereDoesntHave
method to filter all Manufacturers without vehicles before deleting them:
Manufacturer::whereDoesntHave('vehicles')->get();
From the API:
Add a relationship count condition to the query with where clauses.
You can return the count of total vehicles like this:
return [
'count' => Manufacturer::with('vehicles')->find($id)->count()
];
Now you can just check the count.
This will return boolean on whether there is an vehicles on the manufacturer.
return (Manufacturer::with([
'vehicles'=> function($query){
return $query->limit(1);
}])->find($id)->vehicles);
You can add foreign key and prima key on the vehicles to reduce the number of column being query for performance concern.
return $query->limit(1)->select('id','manufacturer_id');