Cannot read property 'before' of undefined

Hi, I’m just trying to add new users to a mysql DB, which I thought it would be easy :), but I’m getting the error “Cannot read property ‘before’ of undefined”. I have tried a lot of changes with no effect and i don’t know what I’m doing wrong.
Please, could you help me?
Thanks in advance.

Here is the error

Cannot read property ‘before’ of undefined

And the code for “UserController.js”

‘use strict’

const User = use(’…/Models/User’);

class UserController {

async store ({ request, response }) {
const { name, username, email, addres, password } = request.all();
const user = await User.create ({ 
          name,
          username,
          email,
          addres,
          password
          });

    return user;
};

}

module.exports = UserController

And if I try with this code:

‘use strict’

const User = use(’…/Models/User’);

class UserController {
async store({ request, response }) {
const params = request.all();
const username = await User.query().where(‘username’, username).firstOrFail();
let name = params.name;
let addres = params.addres;
let email = params.email;
let password = params.password;

    let user = new User();
    await user.register(name, username, addres, email, password);

    console.log(user);
    return response.send(user);
    
};

}

module.exports = UserController

I got this error:

Cannot read property ‘iterator’ of undefined

Please, could you help me?

1 Like

Hi @bermartinez and welcome to our community :smiley:

When using the create() method you must specify the field names. Like:

const user = await User.create({name: "myName", ...})

Try something like this:

const User = use('App/Models/User')
const userData = request.only(['username', 'email', 'age'])

// save and get instance back
const user = await User.create(userData)

When you import the model you have to do it this way:

const ... = use('App/Models/<youModel>')

Don’t hesitate if you have any further questions :slightly_smiling_face:

4 Likes

Thank you so much! I did in that way and it works perfect.

1 Like