skip to Main Content

I’m new to laravel and my code is working before but I changed "name" to "username" then if I click submit it says it doesn’t have a default value.

class UserSignup extends Controller { 
    public function register(Request $request) {

        $validatedData = $request->validate([
            'username' => ['required', 'string','max:255', Rule::unique('users')],
            'email' => ['required', 'email', 'max:255', Rule::unique('users')],
            'password' => 'required|min:8' 
        ]);

        $validatedData['password'] = bcrypt($validatedData['password']); 

        $user = User::create($validatedData);

return response()->json(['message' => 'User created successfully!', 'user' => $user]);
    } 
}

I tried changing the "name" to "username" as shown below

$validatedData = $request->validate([
            'username' => ['required', 'string','max:255', Rule::unique('users')],
            'email' => ['required', 'email', 'max:255', Rule::unique('users')],
            'password' => 'required|min:8' 
        ]); 

After clicking submit there is an error that says it doesn’t have a default value.

I just want the ‘username’ to be put in the database.

2

Answers


  1. Chosen as BEST ANSWER

    I just put username in app.php and it worked

    protected $fillable = [
            'username',
            'name',
            'email',
            'password',
        ];
    

  2. You might set name value to not nullable in your database (and migration). You have 2 options if you want to have name and username properties as well:

    1. Set a default value for your name property (or set it to nullable) and add username property in your database using migration.

    2. Create a name field in your registration form and in your request validation as well and now you can add it into your database record.

    Hint: in your model file (User.php) you have to add every property you want to fill to the $fillable property:

    protected $fillable = ['name', 'username', ...];
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search