Search code examples
laravelvalidationerror-handling

Laravel Blade error directive to PHP equivalent


I'm having trouble understanding the logic behind the Laravel @error blade directive. How does it work with $message enclosed within the @error directive? How does it know which $message to display? I would like to understand the PHP equivalent and how it operates behind the scenes.

@error('name')
   <span class="invalid-feedback" role="alert">
     <strong>{{ $message }}</strong>
   </span>
@enderror

Solution

  • See framework code. https://github.com/laravel/framework/blob/11.x/src/Illuminate/View/Compilers/Concerns/CompilesErrors.php

    The first commit is easier to understand. https://github.com/laravel/framework/commit/d5b80d727b6e426ce424be79b6016838c368504c

    Similar code in older Laravel. @error just shortened this.

    @if ($errors->has('name'))
        <span class="invalid-feedback" role="alert">
            <strong>{{ $errors->first('name') }}</strong>
        </span>
    @endif
    

    https://github.com/laravel/framework/blob/5.8/src/Illuminate/Auth/Console/stubs/make/views/auth/register.stub#L20