Matt Komarnicki
Matt Komarnicki

Reputation: 5422

Laravel 5.1 - Give me the very recent row - lastOrFail

According to the official documentation:

The findOrFail and firstOrFail methods will retrieve the first result of the query.

Cool. I would like something opposite.

Let's assume that I have a table with bunch of columns where multiple rows can have the same type_id and can belong to the same person_id.

I can obviously create queryScope or raw query but maybe you know something like lastOrFail?

Simply it would to return the most recent row from all that fulfil a particular condition. Something like:

$model = $this->makeModel()
            ->where('person_id', '=', $personId)
            ->where('type_id', '=', $typeId)
            ->lastOrFail();

Did you know something like that or do you see a need that this should be implemented in Laravel natively by Taylor?

Upvotes: 4

Views: 968

Answers (1)

Joseph Silber
Joseph Silber

Reputation: 220136

If you order the items in reverse, firstOrFail will give you the last item:

$query = Model::where('person_id', $personId)->where('type_id', $typeId);

$model = $query->latest()->firstOrFail();

Upvotes: 6

Related Questions