简体   繁体   中英

With() vs Compact() in Laravel

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

Which one is more efficient ?

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.

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.

compact is php function :

compact — Create array containing variables and their values

compact() takes a variable number of parameters. Each parameter can be either a string containing the name of the variable, or an array of variable names. The array can contain other arrays of variable names inside it; compact() handles it recursively.

Method with() on Eloquent model enables for you eager loading.

Sometimes you may need to eager load several different relationships in a single operation. To do so, you can just pass additional arguments to the with method:

$userss = App\User::with(['name', 'email'])->get();

when you want to pass multiple variables into a view One way to do so involves passing them into the with method using an array:

public function index()
{

    $data = array('name' => 'some one',
                  'email' => 'someone@gmail.com',
                  'date' => date('Y-m-d'));  

    return view('welcome')->with($data);

}

You could also use multiple with methods, like so:

return view('welcome')->with('name', 'some one')->with('email','someone@gmail.com)->with('date', date('Y-m-d'));

if you needed to pass along more than two variables. You can save some typing by using PHP's compact() function:

$name = 'some one';
$email= 'someone@gmail.com';
$date = date('Y-m-d');
return view('welcome', compact('name','email', 'date'));

or,if you needed to pass multiple arrays to a view you can use compact() function:

$array1 = ... ;
$array2 = ... ;
$array3 = ... ;
return view('welcome', compact('array1', 'array2', 'array3');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM