With() vs Compact() in Laravel

|▌冷眼眸甩不掉的悲伤 提交于 2021-02-20 10:12:41

问题


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

Which one is more efficient ?


回答1:


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.




回答2:


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.




回答3:


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');


来源:https://stackoverflow.com/questions/44963889/with-vs-compact-in-laravel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!