Return the last record in a One to many Eloquent Relation using Laravel
You can use first()
instead of get()
. So it'll get a single model instance.
get()
method give a collection and first()
method give you a single model instance.
User::with(
$this->particulars()
)->orderBy('id', 'desc')->first()
Or you can use latest()
to get the last inserted record.
User::with(
$this->particulars()
)->latest()->first()
->latest()
fetches the most recent set of data from the Database. In short, it sorts the data fetched, using the created_at
column to chronologically order the data.
Edit:-
As you wanted to get the last record of the relationship you can do as below.
User::with('ejob', function($query) {
return $query->latest()->first();
})->get();
// in your case
public function currentJob()
{
return $this->hasOne(Ejob::class, ...)->latestOfMany();
// order by by how ever you need it ordered to get the latest
}
// another example
public function latestPerformance()
{
return $this->hasOne(Performance::class)->latestOfMany();
}
You could define another relationship method for the same relationship but define it as a Has One instead of a Has Many:
public function currentJob()
{
return $this->hasOne(Ejob::class, ...)->latest();
// order by by how ever you need it ordered to get the latest
}
Then you could eager load that instead of the ejob
relationship where needed.