Laravel中with()和compact()有什么区别 [英] What's the difference between with() and compact() in Laravel

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

问题描述

在这两个示例中,Laravel中的功能with()compact()有什么区别:

What's the difference between the functions with() and compact() in Laravel in these two examples:

示例1:

return View::make('books.index')->with('booksList', $booksList);

示例2:

return View::make('books.index',compact('booksList'));

推荐答案

compact()

Well compact() is a PHP function that converts a list of variables into an associative array where the key is the variable name and the value the actual value of that variable.

实际的问题应该是:两者之间有什么区别

The actual question should be: What is the difference between

return View::make('books.index')->with('booksList', $booksList);

return View::make('books.index', array('booksList' => $booksList));

答案实际上不是一个.他们都将项目添加到视图数据中.

The answer there isn't really one. They both add items to the view data.

在语法上,View::make()仅接受一个数组,而with()则接受两个字符串:

Syntax-wise, View::make() only accepts an array while with() takes both, two strings:

with('booksList', $booksList);

或可能包含多个变量的数组:

Or an array that can possibly hold multiple variables:

with(array('booksList' => $booksList, 'foo' => $bar));

这也意味着compact()也可以与with()一起使用:

This also means that compact() can be used with with() as well:

return View::make('books.index')->with(compact($booksList));

这篇关于Laravel中with()和compact()有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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