How to Display Validation Errors on View Page in Laravel

Here is a quick reference tutorial to demonstrate how to display validation errors on view page in Laravel. As you must know that Laravel provides out of the box form / data validation.

If the validation fails by default Laravel will send you back to the previous page from which the request was generated and along with that it will send the Error message in session corresponding to the field that failed the validation.

Let’s see how it works. Consider you have a form to add new Products to the database and you form looks something like given below.

Multi page Laravel step-1

Form has example fields like product name, company, availability, price and description. To validate the form data you need to invoke the validate() method on the request object, and Laravel takes care of the rest. Here is how the method looks to which the data gets submitted.

/**
     * Store a newly created product in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
 
        $validatedData = $request->validate([
            'name' => 'required|unique:products',
            'amount' => 'required|numeric',
            'company' => 'required',
            'available' => 'required',
            'description' => 'required',
        ]);
 
        Product::create($request->all());
 
        return redirect('/products');
 
    }

If the validation fails Laravel will redirect you to the create form page and to display the Errors you can use the following template

@if ($errors->any())
    <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif

Here is how the validation Errors will be displayed on the page.

Laravel Validation Form Errors

 

Leave a reply:

Your email address will not be published.

Site Footer