-1

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

Paco Pinazo Guna
  • 117
  • 2
  • 12

1 Answers1

3

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();
Tim Lewis
  • 27,813
  • 13
  • 73
  • 102
  • 1
    Also if you use splice for pagination, that means you are querying all posts in all pages. Better use Skip and Take methods. Even better use ->paginate() function. – M. Tahir Apr 01 '20 at 14:10
  • @M.Tahir Totally agreed; there are better implementations available for pagination, but this is primarily for addressing the specific issue here :) – Tim Lewis Apr 01 '20 at 14:11
  • Yeap, just saying :) – M. Tahir Apr 01 '20 at 14:13
  • I understand now! Thanks for explaining! It worked flawlesly! – Paco Pinazo Guna Apr 01 '20 at 14:14
  • Also I will try to improve the pagination because as you say there are better ways! Thanks – Paco Pinazo Guna Apr 01 '20 at 14:15
  • @PacoPinazoGuna No problem! Understanding the current class, especially with method chaining like this is something that comes with practice, but eventually it'll make perfect sense :) And yeah, this works for smaller tables, but once you get into a large amount of records, this approach will grind to a halt. – Tim Lewis Apr 01 '20 at 14:16