Laravel display validation fail error messages in blade file

How to show laravel validation fail errors in blade file.



Laravel validation rule in controller

You can use validate() method OR Validator::make() for checking validation rules in the controller.

App/Http/Controllers/UserController.php
<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;

class UserController extends Controller
{
  public function store(Request $request) {
    $request->validate([
      'email' => 'required|unique:users|max:20|min:5',
      'name' => 'required|max:100'
    ]);
  }
}

Validation errors show in blade file

If any rule fails laravel validation method automatically redirects to the back url with error messages. An $errors variable is shared with all of your application's views by the Illuminate\View\Middleware\ShareErrorsFromSession middleware. So you can use the $errors variable in your blade file for printing errors.

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

Validation error message by field name

You can also display error messages by field name see the below example.

  <input type="text" name="email">
  @if($errors->has('email'))
      <div class="error">{{ $errors->first('email') }}</div>
  @endif

  <input type="text" name="name">
  @if($errors->has('name'))
      <div class="error">{{ $errors->first('name') }}</div>
  @endif
php laravel developer anmol sharma

Anmol Sharma

I am a software engineer and have experience in web development technologies like php, Laravel, Codeigniter, javascript, jquery, bootstrap and I like to share my deep knowledge by these blogs.

Random tutorial links