What's the difference between the functions with()
and compact()
in Laravel in these two examples:
Example 1:
return View::make('books.index')->with('booksList', $booksList);
Example 2:
return View::make('books.index',compact('booksList'));
Well compact()
is a PHP function that converts a list of variables into an associative array where the key is the variable name and the value the actual value of that variable.
The actual question should be: What is the difference between
return View::make('books.index')->with('booksList', $booksList);
and
return View::make('books.index', array('booksList' => $booksList));
The answer there isn't really one. They both add items to the view data.
Syntax-wise, View::make()
only accepts an array while with()
takes both, two strings:
with('booksList', $booksList);
Or an array that can possibly hold multiple variables:
with(array('booksList' => $booksList, 'foo' => $bar));
This also means that compact()
can be used with with()
as well:
return View::make('books.index')->with(compact($booksList));
The compact method passes array data to Constructor which is stored to $data
Class attribute :
public function __construct(Factory $factory, EngineInterface $engine, $view, $path, $data = array())
{
$this->view = $view;
$this->path = $path;
$this->engine = $engine;
$this->factory = $factory;
$this->data = $data instanceof Arrayable ? $data->toArray() : (array) $data;
}
While with()
method accepts an array or a string, and in case it is an array it performs array_merge on the parameter otherwise it appends the data to a key which you passed as a paramter to $data
attribute, so if you use constructor you're forced to pass an array
, while with()
accepts a single key with a value.
public function with($key, $value = null)
{
if (is_array($key))
{
$this->data = array_merge($this->data, $key);
}
else
{
$this->data[$key] = $value;
}
return $this;
}