LARAVEL Call to undefined method Illuminate\Database\Eloquent\Builder::splice()

Paco Pinazo Guna :

I am trying to select some atributes of the table Animals and at the same time selecting their photos.

The problem is that in my case I want to select 20 animals depending on the page (For example, if I am in page 2 I want to take the animals between 20-40

I am doing an splice for that, but I don't know how to make it work, it throws me that error.

Anyobody knows why or how?

Many thanks in advance! Code

$cantidad is the quantity of animals I want to take $pagina is the page

Tim Lewis :

You need to be aware of the class you're working with, especially Builder vs Collection

All queries in Laravel (Animal::select(...)) are instances of the Builder class until a closure (->get(), ->first(), etc) is called. Since you're not using one of those closures before calling ->splice(), you're attempting to call this method on a class (Builder) that doesn't have it. The Collection class has this method:

https://laravel.com/docs/7.x/collections#method-splice

So you need to use ->get() before ->splice():

return Animal::select(...)
->join(...)
->where(...)
->get()
->splice(...)
->toJson();

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=386258&siteId=1