What does compact() do in Laravel?
First of all
compact() is not a Laravel function. It is a PHP function. Let me first tell you what it does in PHP.
Compact creates an array containing variables and their values. All of the arguments that we pass to the compact function, it looks for a variable with that name in the currently available variables and adds it to the output array. In the output array, variable names becomes the key and the contents of the variable becomes the value for that key. Any strings that are not set will simply be skipped.
Also compact() works recursively, so you can use nested arrays as well.
- $name = "Hamza Ali";
- $city = "Lahore";
- $country = "Pakistan";
- $location = ["city", "country"];
- $output = compact("name", $location, "unavailable");
The output array looks like this:
- Array ( [name] => Hamza Ali [city] => Lahore [country] => Pakistan )
Compact function in Laravel
We mostly use compact in Laravel to send the values to the view. Something like this:
- $user = User::all();
- return view('index', compact('user'));
Laravel expects an array to be passed to the view helper function. Second argument in view helper function is an array that where keys are the names of the variable and the value are the contents of those variables. These variables will be available in our views to be used.
You can also use
extract PHP function to import variables from an associative array like the one created from the
extract will import variables into the current symbol table from an array.
Learn more about Laravel on my blog
a way to pass variable to views in laravel is use with function . look like this
Instead of using this type of passing data, you can use compact() to passing data.
compact is a php function that allows you create an array with variable names and their values. variable names must be pass to compact function as string argument and then, you with receive an array.
- $pagetitle = 'First Page';
- $username = 'JigarTala';
- $fullname = 'John Tala';
- $variables = compact("pagetitle","username","fullname");
- echo "<pre>".print_r($variables)."<pre>";
and you will see something like this.
- [pagetitle] => First Page
- [username] => JigarTala
- [fullname] => John Tala
and instead of using “with” function for pass data to views, you can use compact and write code look like this
for using compact function, first argument is required, but second or more is optional. this function exist from php 4
you can read document in