简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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