Last Updated: May 31, 2021
·
3.617K
· ariflogic

Anonymous PHP Function in Laravel

Laterally i've realize that laravel support php anonymous style so we can implement such a javascript function usage but surely it hard for me to do for first time

For simple usage, they display an example like this

$users = User::with(array('posts' => function($query)
{
    $query->where('title', 'like', '%first%');
}))->get();

What if the user wanted to make the third parameter is filled with variable. When i check it out with replacing those '%first%' word with any global variable, it ruins the structure, and it happend to me.

$title = 'heirlom of marineford';
$users = User::with(array('posts' => function($query)
{
    $query->where('title', 'like', $title);
}))->get();

After searching to PHP documentation, i found that the technique to passing parameter to that anonymous function by extending function block with use() so the function would assume to use all variable that defined by the use() section

$title = 'heirlom of marineford';
$users = User::with(array('posts' => function($query) use($title)
{
    $query->where('title', 'like', $title);
}))->get();

And its work that way. :)

1 Response
Add your response

Hey, I just wondering. How the $query work in function($query) ?
I think it will useful for me to do that, thanks

over 1 year ago ·