Matthias
Matthias

Reputation: 3

How to get the last entry of a Laravel model which is not NULL on a certain column (Laravel 11)

I would like to get back within a with() the last entry of a modal which is not null on a certain column.

I know that it is possible to simply get the last entry with the following function in the model, but I have not found a way to add a condition.

public function firstCheckedChecklistItem() { return $this->hasOne('App\Models\CheckedChecklistItem')->latestOfMany(); }

This can for example be used like this: $groupMachines = Machine::where('group_id', $group_id)->with('machineType.checklistGroup.currentChecklists.checklistItem.firstCheckedChecklistItem')->get();

With the function described above I only get the last entry, but what I expect would be that I get the last entry which is not NULL in the column done_by

Important is, that i need the last entry in a with()

Upvotes: 0

Views: 42

Answers (1)

UnderIdentityCrisis
UnderIdentityCrisis

Reputation: 86

but I have not found a way to add a condition.

You can add the condition in you model function firstCheckedChecklistItem() or inside with function itself

public function firstCheckedChecklistItem() { 
    return $this->hasOne('App\Models\CheckedChecklistItem')
         ->whereNotNull('done_by')
         ->latestOfMany(); 
}
  ->with(['machineType.checklistGroup.currentChecklists.checklistItem.firstCheckedChecklistItem' => function($query) {
       $query->whereNotNull('done_by');
  }]) 

Reference: How to access model hasMany Relation with where condition?

Upvotes: 0

Related Questions