Is there any difference between with() and compact() ?
Which one is more efficient ?
Is there any difference between with() and compact() ?
Which one is more efficient ?
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.
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');