What does compact() do in Laravel?

3141    1 year ago

What does compact() do in Laravel?

Answers { 2 }
1 year ago

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.

For example:

  1. <?php
  3. $name = "Hamza Ali";
  4. $city = "Lahore";
  5. $country = "Pakistan";
  7. $location = ["city", "country"];
  9. $output = compact("name", $location, "unavailable");

The output array looks like this:

  1. 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:

  1. $user = User::all();
  3. 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 comapct() function. extract will import variables into the current symbol table from an array.

Learn more about Laravel on my blog Tuts for Web - Web Development Tutorials

1 year ago

a way to pass variable to views in laravel is use with function . look like this

  1. view('welcome')->with('pagetitle',$pagetitle)
  2. ->with('username',$username)
  3. ->with('fullname',$fullname);

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.

  1. $pagetitle = 'First Page';
  2. $username = 'JigarTala';
  3. $fullname = 'John Tala';
  5. $variables = compact("pagetitle","username","fullname");
  6. echo "<pre>".print_r($variables)."<pre>";

and you will see something like this.

  1. Array
  2. (
  3. [pagetitle] => First Page
  4. [username] => JigarTala
  5. [fullname] => John Tala
  6. )

and instead of using “with” function for pass data to views, you can use compact and write code look like this

  1. view('welcome',compact("firstvar","secondvar"));

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 official php website