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

こ雲淡風輕ζ 提交于 2020-12-15 08:34:57

问题


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.


回答1:


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




回答2:


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

these two are same as view() second argument can be null or array, compact is a php function which take variable and generate associative array based on variable

and

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

in this code view() laravel helper don't have second argument so yo can use with() function as chaining method and send data to view



来源:https://stackoverflow.com/questions/64220632/what-is-the-difference-between-with-compact-and-array-in-when-return-view-in-la

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