Skip to content
Advertisement

How to generate and set username in Laravel eloquent?

I have some fields in user table:

JavaScript

Here I need to generate and save an userName automatically where the user will provide only firstname & lastName. I have tried something like this but not sure about the piece of code.

User.php

JavaScript

So whenever I’m trying to migrate & seed it’s showing

Field ‘userName’ doesn’t have a default value

The seeder is

JavaScript

Advertisement

Answer

What you’re looking for is Model events.

First define a static boot method on your model. In there you can then run your username generation code.

JavaScript

This will intercept the creation of your model, and generate the username.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement