mercredi 1 avril 2020

How to get the last record using Eloquent scope?

I have a Posts table structured like this:

enter image description here

Now I'm trying to get the latest post which is obviously the record with id = 2.

I have this in my theme page posts.htm:

[builderList postLatest]
modelClass = "Me\Articles\Models\Posts"
scope = "scopeLatest"
scopeValue = ""
displayColumn = "title"
noRecordsMessage = "No records found"
detailsPage = "-"
detailsUrlParameter = "slug"
pageNumber = ""

in my model Posts I have:

public function scopeLatest($query)
{
  return $query->orderBy('created_at','desc')->first();
}

But this one is returning both records. I also tried using latest()

return $query->latest();

And this one gives me the error:

Maximum function nesting level of '1000' reached, aborting!

Even tried passing parameter like latest('created_at') but got the same error.

Tried dumping dd($query->orderBy('created_at','desc')->first()->toSql()) and got select * from posts where posts.deleted_at is null

  1. Why first() is not limiting to 1 record?
  2. Why latest() is throwing me Maximum error? Is this version specific bug? It seems I cant find documentation related to it. I have Laravel 5.5.48.

I'm not sure now what can I use. Maybe I'm doing something wrong here. I just need to get the latest post.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire