Reputation: 7128
How can I get user_id
= null?
Logic:
I have testimonial where I can fill user info manually or just select one of my existing users, the problem is when I try to save testimonial with manual user i get The user id must be a number.
error.
here is my store method:
$this->validate($request, array(
// rest of code
'user_id' => 'nullable|numeric',
));
$testimonial = new Testimonial;
// rest of code
$testimonial->user_id = $request->input('user_id');
// rest of code
This is my form:
{{ Form::label('user_id', 'User') }}
<select class="form-control" name="user_id">
<option>Select User</option>
@foreach($users as $user)
<option value="{{ $user->id }}">{{ $user->username }}</option>
@endforeach
</select>
Here is my schema:
Schema::create('testimonials', function (Blueprint $table) {
// rest of code
$table->integer('user_id')->unsigned()->nullable();
});
Schema::table('testimonials', function (Blueprint $table) {
// rest of code
$table->foreign('user_id')->references('id')->on('users');
});
How can I pass to accept null on this field?
Upvotes: 1
Views: 859
Reputation: 19781
The error message indicates a validation failure and not a database problem. Your database will accept null values since testimonials.user_id is nullable.
The next step in debugging would be to check what $request->input('user_id')
really is. You would need to temporarily disable the validation rules to accomplish this.
dd($request->input('user_id'));
You'll find that an option without value will use it's text as value. You're not sending an empty string, you're sending the string "Select User" which of course isn't numeric. Instead, change your html code to let that option have an empty value.
<option value="">Select User</option>
Upvotes: 2
Reputation: 3488
Since your user_id is acting as a foreign key
in testimonials table, it should be present in users
table also.
When you manually try to enter the record, probably you are assigning it the id that is not present in users table.
You can't have a foreign key
and a NULL
at the same time. Just remove the constraint and it will work fine for both scenarios
Upvotes: -1
Reputation: 11636
change
$testimonial->user_id = $request->input('user_id');
to
$testimonial->user_id = (int) $request->input('user_id');
Upvotes: 0