Laravel Check If Related Model Exists

Laravel Check If Related Model Exists

In php 7.2+ you can't use count on the relation object, so there's no one-fits-all method for all relations. Use query method instead as @tremby provided below:

$model->relation()->exists()

generic solution working on all the relation types (pre php 7.2):

if (count($model->relation))
{
// exists
}

This will work for every relation since dynamic properties return Model or Collection. Both implement ArrayAccess.

So it goes like this:

single relations: hasOne / belongsTo / morphTo / morphOne

// no related model
$model->relation; // null
count($model->relation); // 0 evaluates to false

// there is one
$model->relation; // Eloquent Model
count($model->relation); // 1 evaluates to true

to-many relations: hasMany / belongsToMany / morphMany / morphToMany / morphedByMany

// no related collection
$model->relation; // Collection with 0 items evaluates to true
count($model->relation); // 0 evaluates to false

// there are related models
$model->relation; // Collection with 1 or more items, evaluates to true as well
count($model->relation); // int > 0 that evaluates to true

Laravel Checking If a Record Exists

It depends if you want to work with the user afterwards or only check if one exists.

If you want to use the user object if it exists:

$user = User::where('email', '=', Input::get('email'))->first();
if ($user === null) {
// user doesn't exist
}

And if you only want to check

if (User::where('email', '=', Input::get('email'))->count() > 0) {
// user found
}

Or even nicer

if (User::where('email', '=', Input::get('email'))->exists()) {
// user found
}

Laravel check if relation is empty

There are a variety of ways to do this.

#1 In the query itself, you can filter models that do not have any related items:

Model::has('posts')->get()

#2 Once you have a model, if you already have loaded the collection (which below #4 checks), you can call the count() method of the collection:

$model->posts->count();

#3 If you want to check without loading the relation, you can run a query on the relation:

$model->posts()->exists()

#4 If you want to check if the collection was eager loaded or not:

if ($model->relationLoaded('posts')) {
// Use the collection, like #2 does...
}

Note: Replace posts with the name of your relationship in the above examples.

Laravel eloquent check if related model exists

Do you have a relationship setup on the Task model to it's parent? Something like:

public function parent() : BelongsTo
{
return $this->belongsTo(__CLASS__, 'parent_id', 'id');
}

If so, you can check the parent task's existence and completed status like:

null !== $task->parent && $task->parent->status === 'completed'

Laravel: How to query a Model Relationship only if it exists

Original answer

What i needed was the whereDoesntHave method.

$surveys = Survey::whereNotNull('installer_id')
->whereDoesntHave('installation.assignments', fn ($query) => $query->where('status', 2))
->get();

Laravel - Filter the relation of a relation if it exists

This is the result query if I understood correctly :

$results = ObjectA::where('is_something', true)
->whereHas('objectB', function($subQ) {
$subQ->whereRelation('objectC', 'is_something', true);
})
->get();

reference for the whereRelation : https://laravel.com/docs/9.x/eloquent-relationships#inline-relationship-existence-queries

Laravel: Model function to check if relationship exists

You could define an accessor or a function within your parent model.

Something like this in your Customer model:

public function getLatestContactAddress()
{
return optional($this->latestContact)->address;
}

And call it like this:

$customer->getLatestContactAddress();

Check if belongsToMany relation exists - Laravel

I think the official way to do this is to do:

$client = Client::find(1);
$exists = $client->products->contains($product_id);

It's somewhat wasteful in that it'll do the SELECT query, get all results into a Collection and then finally do a foreach over the Collection to find a model with the ID you pass in. However, it doesn't require modelling the pivot table.

If you don't like the wastefulness of that, you could do it yourself in SQL/Query Builder, which also wouldn't require modelling the table (nor would it require getting the Client model if you don't already have it for other purposes:

$exists = DB::table('client_product')
->whereClientId($client_id)
->whereProductId($product_id)
->count() > 0;


Related Topics



Leave a reply



Submit