Taylor Swift Taylor Swift - 1 year ago 62
PHP Question

Best practice to pass many arrays and long variables to view in Laravel

Please consider this method in this controller:

public function showPage() {

$settings = [
'show_box' => 'Show box',
'coolstuff' => 'Some text',
'ss_text' => 'Anotehr text',
'blur_haha' => 'Nice text',
'nice_s' => 'Nice hahahaha',

$text = [
'hey' => 'Show box',
'nice_text' => 'Some text',
'yes_text' => 'Anotehr text',
'no_hahaaha' => 'Nice text',
'cool_text' => 'Nice hahahaha',

return view('page', compact('settings');

As you can see, the method mostly contains variable declarations for arrays. Now lets say there are like 10 variables like this.

What would be the best practice to do this? There's nothing wrong with this but it's not-at-all clean. It is extremely crowded.

I was wondering if maybe I could declare them somewhere else and pass the variable to the controller.

Thank you.

Answer Source

If your arrays and variables are static, it's best not to clutter your controllers (or any PHP classes for that matter).

I would define a config file. Say config/settings.php for example:

// config/settings.php
return [
    'show_box' => 'Show box',
    'coolstuff'   => 'Some text',
    'ss_text'   => 'Anotehr text',
    'blur_haha'   => 'Nice text',
    'nice_s'   => 'Nice hahahaha',

Now in your controller you can just do this:

return view('page', ['settings' => Config::get('settings')];

If your controller needed to inspect, add to, or modify a couple settings first:

$settings = array_merge(Config::get('settings'), [
    "new" => "some text",
    "show_box" => "change this value"
return view('page', ['settings' => $settings]);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download