0

I queried to get info from a table with a manytomany relationship like this

$userList = UserListing::where('user_id', $user->id)->with("objects")->paginate(10);

Now, i want to limit the amount of results in the "Objects" table, but at the same time i want to know how many objects are in total.

        $userList = UserListing::where('user_id', $user->id)->with(["objects"=> function($query) {
             $query->take(2);
        }])->paginate(10);

But by doing this, i can't get the total of objects since i limited it to 2, then i tried to process the info like this

$userList = UserListing::where('user_id', $user->id)->with("objects")->paginate(10);

foreach ($userList as $key => $value) {
    $l = count($value["objects"]);
    $value["objects"] = $value["objects"]->take(2);
    $value["number_objects"] = $l;
}

But apparently this did not replace the collection value["objects"], since it still returned 3 objects, despite supposedly being reduced with $value["objects"] = $value["objects"]->take(2);. How can i replace the collection with the reduced one?

Efraín
  • 453
  • 1
  • 7
  • 13

1 Answers1

0

So, i kept investigating, and noted that userList was a LengthAwarePaginator object, which by property apparently is inmutable in its original fields(Meaning you can add new ones, but not delete/modify the already existent). Knowing this, i searched a little more and found this answer:

https://stackoverflow.com/a/49133519/7228093

Which basically creates a new LenghtAwarePaginator from the original one, allowing you to modify the fields. If someone finds in this situation, this may be a good option(The transform method of collections did not work by the way, only this one).

Efraín
  • 453
  • 1
  • 7
  • 13