简体   繁体   English

通过laravel orm进行查看

[英]passing laravel orm to view

I'm working with laravel 4 and am unsure about the best practice-- is it considered a good idea to pass the Eloquent object directly to the view, or is it best to use the toArray method on it before passing it in? 我正在使用laravel 4,不确定最佳实践-将Eloquent对象直接传递给视图是否是一个好主意,还是最好在传递给它之前使用toArray方法?

Eg. 例如。 this: 这个:

public function index()
{
    $users  = Users::all();
    return View::make('users.index', array('users' => $users));
}

or this: 或这个:

public function index()
{
    $users  = Users::all()->toArray();
    return View::make('users.index', array('users' => $users));
}

or something else entirely? 还是完全其他的东西?

I think making an array from the object and wrapping it in another to pass to the view is an overhead, when you can directly pass the object to the view. 我认为,当您可以将对象直接传递给视图时,从该对象创建一个数组并将其包装在另一个数组中以传递给视图是一项开销。

Try by 试试看

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

仅向对象发送视图是完全可以接受的,并且在大多数情况下都建议这样做。

return View::make('users.index')->with(array('users' => $users));

You should use: 您应该使用:

$users  = Users::all();
return View::make('users.index')->with(array('users' => $users));

or even 甚至

return View::make('users.index')->with(array('users' => Users::all()));

in this case. 在这种情况下。

You don't need to convert your object to array. 您不需要将对象转换为数组。 In your view (Blade or not) you can display object properties and not array elements and it's really fine to do that. 在您的视图中(无论是否带刀片),您都可以显示对象属性,而不是数组元素,这样做确实很好。 Moreover you can also use accessor if you have set any and if you convert your object to array you won't be able to do that 此外,如果您已设置访问器,并且还可以将对象转换为数组,则也可以使用访问器

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM