I have an object with some relationships and I need to check if these relations are empty or not, I'm trying to check with is_null, isset, != undefined, etc but nothing works, here is the relationship I get when it's empty :
object(Illuminate\Database\Eloquent\Collection)#197 (1) { ["items":protected]=> array(0) { } }
Is there a way to check this easily ? Thanks.
whereHas() works basically the same as has() but allows you to specify additional filters for the related model to check.
Solution. with() is generally used with eager loading, which is a quick way to pull related models. Basically, it means that, along with the main model, Laravel will preload the listed relationship(s). This is beneficial when you need to load additional data and want to avoid making N+1 DB bad practices.
There are a variety of ways to do this.
In the query itself, you can filter models that do not have any related items:
Model::has('relation')->get()
Once you have a model, if you already have loaded the collection, you can check the count of the collection:
$model->relation->count();
If you want to check without loading the relation, you can run a query on the relation:
$model->relation()->exists()
Note: Replace relation
with the name of your relationship in the above examples.
If model already have loaded relationship, you can determine the variable is null
or call isEmpty()
to check related items:
// For one relation: if ( $model->relation ) { // ... } else { // $model->relation is null } // For many relations: if ( $model->relation->isEmpty() ) { // ... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With