Laravel - How to define variabe inside $query function?

Viewed 77

I have this $query Function in my Controller. It works. But when i try to add a variable inside it, it's not working. this is my Full function

$setting = DB::table('settings')->where('id','=','1')->get();
     foreach($setting as $st)
     $date1 = $st->date1;
     $date2 = $st ->date2;

$accounts =  Account::with(['subaccount' => function($query){
             $query->with(['subaccountinvoice'=> function($query){
             $query->where('validate', '=','1')->whereBetween('updated_at', [$date1, $date2]);}])->get();
         }])->get();

Variables $date1 and $date2 are not defined because they are insidd Query Function

1 Answers

In order to inherit a variable within a closure in PHP you need to pass it to the closure using the use keyword.

Change your accounts code to this:

$accounts =  Account::with(['subaccount' => function($query) use ($date1, $date2) {
                 $query->with(['subaccountinvoice'=> function($query) use ($date1, $date2) {
                    $query->where('validate', '=','1')->whereBetween('updated_at', [$date1, $date2]);}])->get();
             }])->get();
Related