Validation errors for multiple forms on same page Laravel

Updated at 18-May-2021, By samar

Validation errors for multiple forms on same page Laravel

Through the use of the programming language, we will work together to solve the "Validation errors for multiple forms on same page Laravel" puzzle in this lesson.

If you have multiple forms on the same page then you can assign the name to MessageBag which contains the validation errors. It helps you to retrieve the error messages for a specific form using the MessageBag name on the variable $errors.
  • 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