Laravel返回视图时,with,compact和array之间有什么区别 [英] What is the difference between with, compact and array in when return view in laravel

查看:73
本文介绍了Laravel返回视图时,with,compact和array之间有什么区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有点困惑我想知道这三个收益之间的区别:

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

返回视图('post',['post'=> $ post]);

返回视图('post',compact('post'));

返回视图('post')-> with('post'=> $ post);

所以,有人可以帮我简单地解释一下区别吗.

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

推荐答案

Array :您可以将数据数组传递给视图,例如:

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

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

以这种方式传递信息时,数据应为具有键/值对的数组.在视图内部,然后可以使用其对应的键访问每个值,例如<?php echo $ key;.?>

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():作为将完整的数组数据传递到

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():您可以使用 compact()来传递数据,而不是使用这种类型的传递数据. compact() 是内置的 php函数,可让您使用变量名及其值创建一个数组.变量名必须作为字符串参数传递给Compact函数,然后,您会收到一个 array ,因此,紧凑方法就像第一种方法一样,将变量传递给视图:


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

请参阅将数据传递给视图的官方文档

这篇关于Laravel返回视图时,with,compact和array之间有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆