Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Laravel: How to fix not detecting "username" input

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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', ...];
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading