Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

With() vs Compact() in Laravel

Is there any difference between with() and compact() ?

Which one is more efficient ?

like image 629
Animesh Avatar asked Jul 07 '17 06:07

Animesh


People also ask

What is compact () in laravel?

The compact() function creates an array from variables and their values.

What is the use of compact () function?

The compact() function is an inbuilt function in PHP and it is used to create an array using variables. This function is opposite of extract() function. It creates an associative array whose keys are variable names and their corresponding values are array values.

What does get () do in laravel?

For creating ::where statements, you will use get() and first() methods. The first() method will return only one record, while the get() method will return an array of records that you can loop over. Also, the find() method can be used with an array of primary keys, which will return a collection of matching records.

What does => mean in laravel?

The difference is that => is the assign operator that is used while creating an array. For example: array(key => value, key2 => value2) And -> is the access operator. It accesses an object's value.


2 Answers

with() is a Laravel function and compact() is a PHP function and have totally different purposes.

with() allows you to pass variables to a view and compact() creates an array from existing variables given as string arguments to it.

See compact() for more info on this matter.

like image 131
baikho Avatar answered Nov 11 '22 20:11

baikho


with() is a method made available by method from one of their classes while compact() is a method that is available by default in PHP The with() cannot be used outside laravel but the compact() can be used anywhere in the PHP script.

The compact() function is used to convert given variable to to array in which the key of the array will be the name of the variable and the value of the array will be the value of the variable.

like image 33
Sagar Gautam Avatar answered Nov 11 '22 21:11

Sagar Gautam