Correctly passing collection of models to Edge

Hey guys,

Simple question. I just want to make sure there’s not a better way of passing model data to my views that I’m missing. The below code works just fine, but the only way I can get the results I’m wanting is to access the .rows property:

async index({view}) {

	const users = await User.all()

	return view.render('welcome', {users: users.rows})
}

I was surprised I couldn’t just return the users variable like this:

	return view.render('welcome', {users: users})

Am I doing this correctly or is there another way? Not a big deal either way, just curious.


WelcomeController.js

const User = use(‘App/Models/User’)

class WelcomeController {

async index({view}) {

	const users = await User.all()

	return view.render('welcome', {users: users.rows})
}

}


welcome.edge

<ul>
  @each(user in users)
    <li> {{ user.username }} </li>
  @endeach
</ul>

Hey @gcopley! :wave:

You should use the method toJSON() to pass a model to a view.
This will compute all of your computed fields, transform your attributes via your special method, format your date and hide attributes you don’t want to have (via hidden()).

1 Like

Thanks @romain.lanz! I tried to locate this somewhere in the docs and couldn’t find an example of using .toJSON() when calling a view (maybe this could be added). Almost all of the examples just return ‘await User.all()’ from the controlller, which implicitly converts it to JSON.

@gcopley Here you go.

http://dev.adonisjs.com/docs/4.0/lucid#_pagination

And I do recommend reading the serializers doc too.

http://dev.adonisjs.com/docs/4.0/serializers

here is an update for 4.1 https://adonisjs.com/docs/4.1/serializers