Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

laravel - get last record

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()

like image 257
Matrix Avatar asked Oct 18 '25 05:10

Matrix


1 Answers

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.

like image 126
Benyi Avatar answered Oct 19 '25 21:10

Benyi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!