Group where
According to the documentation, you can use «where groups». However, it's not clear from the documentation how to pass a variable to a nested function.
The documentation provides the following example:
QB::table('my_table')
->where('my_table.age', 10)
->where(function($q)
{
$q->where('name', 'LIKE', '%usman%');
// You can provide a closure on these wheres too, to nest further.
$q->orWhere('description', 'LIKE', '%usman%');
});
However, when attempting something similar, problems arise:
$search = 'Ale';
QB::table('my_table')
->where('my_table.age', 10)
->where(function($q)
{
$q->where('name', 'LIKE', '%'.$search.'%');
$q->orWhere('description', 'LIKE', '%'.$search.'%');
});
This results in an error about an unknown variable $search.
To pass a variable to a nested function, you can use the use statement in PHP. Here's the modified code:
$search = 'Ale';
QB::table('my_table')
->where('my_table.age', 10)
->where(function($q) use ($search)
{
$q->where('name', 'LIKE', '%'.$search.'%');
$q->orWhere('description', 'LIKE', '%'.$search.'%');
});
By adding use ($search) after the function($q), you can pass the $search variable into the closure.
This should resolve the issue of the unknown variable and allow you to use variables in nested functions.
I'm sorry, I decided to use a translator using ChatGPT to translate my question into English. And he not only translated it but also suggested a solution. Without hesitation, I copied it and wrote it here.
This is so silly and amusing 😁.
Perhaps let this discussion remain here for posterity. Surely, someone else, just like me, may find themselves in a similar situation and come across the solution. At the same time, they can have a good laugh (at my situation) 😄
This made me laugh hard 😆
Thanks!