Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

masterpowers's avatar

Constraining Eager Loads - PHP warning: Missing argument 2 for {closure}() on line 1

Hi this is how my code looks like

$users = App\User::with(['links' => function ($query, $q) {
    $query->where('link', 'like', '%$q%');

}])->get();

The Problem is im getting PHP warning: Missing argument 2 for {closure}() on line 1

If i Try to Remove it and change the %$q% to %iyuri305% which is the name of the link i get this Result

=> Illuminate\Database\Eloquent\Collection {#783
     all: [
       App\User {#801
         username: "supervip",
         links: Illuminate\Database\Eloquent\Collection {#813
           all: [],
         },
       },
       App\User {#809
         username: "yuri",
         links: Illuminate\Database\Eloquent\Collection {#811
           all: [
             App\Link {#753
               link: "iyuri305",
             },
           ],
         },
       },
     ],
   }

I want to Achieve an Effect Where in It Only Return to Me a User With a Link of iyuri305.

And Passing an Argument of $q is the Only Way i Can think of , But it is giving me Error in php artisan tinker.

I havent Tried it Yet Using a View Where i Will Fetch a $q.

Any Comment? Am i Doing it Correct or Not to Achieve the Effect i Want ?

0 likes
1 reply
Ori's avatar

If variable $q is a parameter defined outside of clousure, you need to say clousure to look for it.

$q = "defined outside of scope";

$users = App\User::with(['links' => function ($query) use ($q) {
    $query->where('link', 'like', "%$q%");

}])->get();

Now it will be able to read that variable inside of clousure. For more info take a look at http://php.net/manual/en/functions.anonymous.php

Hope it is what you have been looking for.

5 likes

Please or to participate in this conversation.