I have problem with validating html select. I put rules and all other form controls work fine but only select not show validate message.
Model
class Post extends Model
{
protected $table = 'post';
static $rules = [
'title' => 'required',
'slug' => 'required',
'user_id' => 'required|not_in:0',
'meta_title' => 'required',
'meta_description' => 'required',
'post_category_id' => 'required'
];
}
Blade
<div >
{{ Form::label('post_category_id', 'Category') }}
<select name="post_category_id" >
<option value="0">Select Category</option>
@foreach($categories as $category)
<option value="{{ $category->id }}" {{ $category->id == $post->post_category_id ? 'selected' : ''}}>{{ $category->name }}</option>
@endforeach
</select> {!! $errors->first('post_category_id', '<div >:message</div>') !!}
</div>
Controller
public function store(Request $request)
{
request()->validate(Post::$rules);
$post = Post::create($request->all());
Alert::alert('Success', 'Post created successfully.', 'Type');
return redirect()->route('admin.post.index');
}
What i do wrong here?
CodePudding user response:
As far as I see, you have a default value set on your placeholder of the select, so the input will always be valid since its always sent to the backend. take a look at this line : Select Category you're setting a default value, remove it and try again:
in your blade do this:
<div >
{{ Form::label('post_category_id', 'Category') }}
<select name="post_category_id" >
<option>Select Category</option>
@foreach($categories as $category)
<option value="{{ $category->id }}" {{ $category->id == $post->post_category_id ? 'selected' : ''}}>{{ $category->name }}</option>
@endforeach
</select> {!! $errors->first('post_category_id', '<div >:message</div>') !!}
</div>
CodePudding user response:
Even if the option has the value 0 it is still present so, no error will be triggered for "required" rule
Use a disabled option instead
<select name="post_category_id" >
<option disabled>Select a Category</option>
@foreach($categories as $category)
<option value="{{ $category->id }}" {{ $category->id == $post->post_category_id ? 'selected' : ''}}>{{ $category->name }}</option>
@endforeach
</select>