Validation for multiple forms on same page in laravel

Updated at 27-Jul-2021, By samar

Validation for multiple forms on same page in laravel

In this article, we will see how to solve "Validation for multiple forms on same page in laravel".

You can validate multiple forms on the same page in laravel. You have to use the message bag to validate and display the validation error message.
  • Validate form data using validateWithBag method in Laravel 8

    --PATH app\Http\Controllers\<PostController>.php
    // Before class definition
    use Illuminate\Support\Facades\Validator;
    
    // Controller's store method
    public function store(Request $request){
    
        Validator::make($request->all(), [
            'title' => 'required|unique:posts|max:255',
            'body' => 'required',
        ])->validateWithBag('post');
        
        // Code after validation
    }
    
  • Display errors using MessageBag instance from the $errors variable

    --PATH resources\views\<post>\<create>.blade.php
    @if($errors->post->any())
    <div class="alert alert-danger alert-dismissible fade show">
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
            <span aria-hidden="true">&amp;times;</span>
        </button>
        <ul class="list-unstyled">
            @foreach($errors->post->all() as $error)
            <li> {{ $error }} </li>
            @endforeach
        </ul>
    </div>
    @endif
    

Back to code snippet queries related laravel