Home  >  Q&A  >  body text

Solve the problem that Laravel cannot detect the "username" input

<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粉060112396P粉060112396431 days ago427

reply all(2)I'll reply

  • P粉799885311

    P粉7998853112023-08-16 09:04:22

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

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

    reply
    0
  • P粉473363527

    P粉4733635272023-08-16 00:24:13

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

    reply
    0
  • Cancelreply