Skip to content
Advertisement

What is the difference between with, compact and array in when return view in laravel

I’m little bit confuse I want to know the difference between those three returns:

return view('post', ['post' => $post]);

return view('post', compact('post'));

return view('post')->with('post'=>$post);

So, can someone explain for me the difference in easy way.

Advertisement

Answer

Array : You may pass an array of data to views, like this :

return view('post', ['post' => $post]);

When passing information in this manner, the data should be an array with key / value pairs. Inside your view, you can then access each value using its corresponding key, such as <?php echo $key; ?>


with() : As an alternative to passing a complete array of data to the view helper function, you may use the with method to add individual pieces of data to the view :

return view('post')->with('post' => $post);
// multiple with method
return view('post')->with('post' => $post)->with('comment' => $comment);

compact() : Instead of using this type of passing data, you can use compact() to passing data. compact() is a built in php function that allows you create an array with variable names and their values. variable names must be pass to compact function as string argument and then, you with receive an array, so compact passing the varibale on your view like the first method :

return view('post', compact('post'));
// same as
return view('post', ['post' => $post]);

See the official documentation of Passing Data To Views

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement