Solve the problem that Laravel cannot detect the "username" input
P粉060112396
2023-08-15 14:50:48
<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>
I just added the username in app.php and then it worked
You can set the
name
value to non-empty in the database (and migrations). If you also want to have thename
andusername
attributes, there are two options:Set a default value for the
name
attribute (or make it nullable) and add theusername
attribute using migrations in the database.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: