Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Not able to access local variable inside function in Laravel 8

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Appreciate it if someone could help with this!

>Solution :

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);           
                    }                       
})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading