当前位置:网站首页>Example of parameter passing from laravel query constructor to closure method

Example of parameter passing from laravel query constructor to closure method

2022-06-26 12:22:00 Special sword

Laravel The query constructor closure method accepts parameters

scene :

Set external parameters $status Pass on to where Use inside the closure function .

Code demonstration :

/** *  Examples of use  */
public function test5(Request $request){
    
	$status = 1;// External parameters ( The status value  1: Through auditing ,2: Failed to pass the audit )
	// Get approved products 
	$data= Goods::where(function ($query) use($status) {
    
        $query->where('status', $status);
    })
    ->select('id','name','status')->get();
    //dd($data->toArray());//laravel Directly use the built-in... Within the framework dd() Function to print . toArray() You can convert the result set from the query into an array , This makes the data clearer .
	pring_r($data);die;// Print the results 
}


/** *  Code interpretation  */
public function demoExplain(Request $request){
    
	$status = 1;// You need to where Parameters passed in closure methods 
	//$query It's fixed writing , Don't move . 
	// use ($ Need to think wherr The variable name passed by the closure method ) 
	//  Multiple parameters in use() There is , Division of no.   Such as : use($ Parameters A,$ Parameters B,$ Parameters C)
	$data= Goods::where(function ($query) use($status) {
    
		//$status The name of the variable passed in , Here you can use dd($status) Print the results 
		//dd($status); The result of printing is  1  Same as the variable value defined above , That means it's coming in .
        $query->where('status', $status);
    })
    ->select('id','name','status')->get();
    //dd($data->toArray());//laravel Directly use the built-in... Within the framework dd() Function to print . toArray() You can convert the result set from the query into an array , This makes the data clearer .
	pring_r($data);die;// Print the results 
}

原网站

版权声明
本文为[Special sword]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202170522214835.html