user101289
user101289

Reputation: 10422

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?

Upvotes: 0

Views: 108

Answers (3)

Marcin Nabiałek
Marcin Nabiałek

Reputation: 111869

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

Upvotes: 1

Colin Schoen
Colin Schoen

Reputation: 2600

Sending the view just the object is perfectly acceptable and is what is encouraged in most cases.

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

Upvotes: 1

Mithun Satheesh
Mithun Satheesh

Reputation: 27845

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

Upvotes: 1

Related Questions