skip to Main Content

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 class="form-group">
    {{ Form::label('post_category_id', 'Category') }}
    <select name="post_category_id" class="form-control">
        <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 class="invalid-feedback">: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?

2

Answers


  1. 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 class="form-group">
        {{ Form::label('post_category_id', 'Category') }}
        <select name="post_category_id" class="form-control">
            <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 class="invalid-feedback">:message</div>') !!}
    </div>
    
    Login or Signup to reply.
  2. 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" class="form-control">
        <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>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search