Reputation: 107
I have this query
$user->orders->where('service_id',$request->service_id)->first();
I need to get the last element , How can I do that ?
there is no created_at
column so I can't use latest()
Upvotes: 4
Views: 13578
Reputation: 952
Try latest()
method once more and give them a parameter.
$user->orders()
->where('service_id', $request->service_id)
->latest('id')
->first();
Eloquent's latest()
method:
/**
* Add an "order by" clause for a timestamp to the query.
*
* @param string $column
* @return $this
*/
public function latest($column = null)
{
if (is_null($column)) {
$column = $this->model->getCreatedAtColumn() ?? 'created_at';
}
$this->query->latest($column);
return $this;
}
This method internally uses created_at
, but accepts specific column you want. I suggest that use this method rather than ->orderBy()->frist()
. This gives you more readability and maintainability.
Upvotes: 10
Reputation: 511
$user->orders()->where('service_id', $request->service_id)->orderBy('id', 'DESC')->first();
Upvotes: 5