Solve the problem that Laravel cannot detect the "username" input
P粉060112396
P粉060112396 2023-08-15 14:50:48
0
2
451
<p>I am new to laravel and my code worked before but I changed "name" to "username" and then if I click submit it says it has no default value. </p> <pre class="brush:php;toolbar:false;">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]); } }</pre> <p>I tried changing "name" to "username" as shown below</p> <pre class="brush:php;toolbar:false;">$validatedData = $request->validate([ 'username' => ['required', 'string','max:255', Rule::unique('users')], 'email' => ['required', 'email', 'max:255', Rule::unique('users')], 'password' => 'required|min:8' ]);</pre> <p>After clicking submit, an error appears saying it has no default value. </p> <p>I just want to put 'username' into the database. </p>
P粉060112396
P粉060112396

reply all(2)
P粉799885311

I just added the username in app.php and then it worked

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

You can set the name value to non-empty in the database (and migrations). If you also want to have the name and username attributes, there are two options:

  1. Set a default value for the name attribute (or make it nullable) and add the username attribute using migrations in the database.

  2. Create a name field in the registration form and request validation, now you can add it to the database record.

Tip: In your model file (User.php) you must add each property you want to fill to the $fillable attribute:

protected $fillable = ['name', 'username', ...];
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template