Demers94's avatar

Passing parameters to eager loading condition

Hello everyone,

sorry for the not-so-explicit title, I couldn't find a better way to phrase it. I'm using a standalone version of Eloquent with a little Slim PHP forum I'm building.

I have a Board object with has a hasMany relationship with the topics that have been posted in that board. I'm using a pagination system and passing the current page number to the URL, to calculate the LIMIT and OFFSET (or skip() and take() with the query builder).

Here's my code at hte moment :

$perPages = 15;
$pageOffset = ($page - 1) * $perPages;

// Get the board from the slug
$board = Board::with(array('topics' => function($query, $perPages, $pageOffset){
    $query->skip($pageOffset)->take($perPages);
}))->where("slug", $slug)->first();

$page is the page number which I take from the URL.

How can I pass the $perPages and $pageOffset variables to the closure? I tried adding them as extra parameters as shown below, but I'm getting this error : Missing argument 2 for {closure}()

0 likes
3 replies
bobbybouwmann's avatar
Level 88

You need to pass them to the closure using the use keyword

$board = Board::with(array('topics' => function($query) use ($perPages, $pageOffset) {
    // Your stuff here

This will get the parameter from the parent scope and import it in the scope of the closure ;)

10 likes
Demers94's avatar

@bobbybouwmann Thank you, that worked!

I have another related question though, when using this synthax, how can I eager load multiple things without having to recopy the closure and the constraints ?

For example, let's say that I want to eager load the user who made that post, I can do this : $board = Board::with(array('topics.user' => function($query) use ($perPages, $pageOffset) { //Rest of the code

But what if I also want to get the lastPost of the topic? Or eager load any other relationship that the topic has?

Edit

Nevermind, I solved it by just adding the next "eager load" as the next element in the array, it seems to work even without specyfing the constraint once again, which makes sense. :)

Please or to participate in this conversation.