I need to create a view with more than 20 parameters into a controller.
In Laravel there are many ways to pass parameters into a view:
Method 1: Passing $data as a parameter
public function get_index1(){
$data = array(
'var1' => $var1,
'var2' => $var2,
'var3' => $var3,
'var4' => $var4,
);
// associative array
return View::make('test.index', ['data' => $data]);
// OR with compact()
return View::make('test.index', compact('data', 'otherVariable'));
}
Method 2: Single with
public function get_index2(){
$data = array(
'var1' => $var1,
'var2' => $var2,
'var3' => $var3,
'var4' => $var4,
);
return View::make('test.index')->with($data);
}
Method 3: Multiple with
public function get_index3(){
return View::make('test.index')
->with('var1', $var1)
->with('var2', $var2)
->with('var3', $var3)
->with('var4', $var4);
}
In my case (passing more than 20 parameters) which is the most efficent method and why?
"We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil" - Donald Knuth
While on development you should focus on maintainability rather than performance. Only when you hit performance issues you should start worrying about it, since frequently, optimization comes with the inevitable loss of maintainability.
Of course this is assuming you're on web development and not working on a low level matrix module for the Hadron Super Collider.
So answer is 2.
Just put that much parameters into array and put it there with the method you prefer. You will not notice much efficiency change in either method.
Since i haven't seen the context of the data that is populating $data, i have to guess: Use option two with loop that ends up building out the $data array:
$data = array(
'var1' => $var1,
'var2' => $var2,
'var3' => $var3,
'var4' => $var4,
);
Always use what is seen as the standard practice method, until you yourself find a better method that fits your understanding. From an outside point of view: i would prefer to see two if i was going to edit your code, than have to decipher how you passed the data any other way.