Home > OS >  Not able to access local variable inside function in Laravel 8
Not able to access local variable inside function in Laravel 8

Time:02-17

I'm trying to access a variable inside the function. The array variable has already been declared outside the function.

My code:

$job_bookings = DB::table('job_bookings')
                    
                    ->where('client_id','=',$p1Array['incharge_id'])
                    
                    ->where( function($query) {
                        
                        if( Arr::has($p1Array, 'includeProcessJob') ) {
                            
                            $query  -> where('ndt_job_status_id','=',1)
                                    -> orWhere('ndt_job_status_id','=',2);
                        
                        } else {
                            
                            $query  -> where('ndt_job_status_id','=',1);
                        
                        }
                        
                    })

I'm receiving an undefined $p1Array variable error when executing the code inside the where clause function. the code outside the function ( ->where('client_id','=',$p1Array['incharge_id']) ) , does n't receive any error.

Appreciate it if someone could help with this!

CodePudding user response:

You have to pass that variable(which you want to use) in use().

Like:

->where( function($query) use($p1Array) {}

So your query will be

$job_bookings = DB::table('job_bookings')                                             
                ->where('client_id','=',$p1Array['incharge_id'])                        
                ->where( function($query) use($p1Array) {
                    if( Arr::has($p1Array, 'includeProcessJob') ) {
                        $query->where('ndt_job_status_id','=',1)
                              ->orWhere('ndt_job_status_id','=',2);           
                    } else {                           
                        $query->where('ndt_job_status_id','=',1);           
                    }                       
})
  • Related