In Laravel's Blade templating engine,** you can use the @error and @enderror directives to display validation error messages**. These directives are typically used in conjunction with Laravel's form validation functionality. Here's how you can use them in a Blade file:
Start by performing form validation in your controller method. For example, assuming you have a store method in your controller:
public function store(Request $request)
{
$request->validate([
'category_slug' => 'required|unique:categories,category_slug|regex:/^[\w-]*$/|max:255',
]);
// Code for storing the category
}
In your Blade template, display the input field and use the @error directive to show the validation error message below the input field. For example:
html
<form action="{{ route('categories.store') }}" method="POST">
@csrf
<input type="text" name="category_slug" value="{{ old('category_slug') }}" placeholder="Category Slug">
@error('category_slug')
<span class="text-red-500">{{ $message }}</span>
@enderror
<button type="submit">Submit</button>
</form>
In the code above, the @error directive is used to display the error message related to the category_slug field. If there is a validation error for that field, the error message specified in the validation rules will be displayed within the element. The $message variable holds the error message associated with the field.
Additionally, you can use the @enderror directive to achieve the same result as @error('category_slug'). Here's an alternative way to display the error message:
html
<form action="{{ route('categories.store') }}" method="POST">
@csrf
<input type="text" name="category_slug" value="{{ old('category_slug') }}" placeholder="Category Slug">
@enderror('category_slug')
<span class="text-red-500">{{ $message }}</span>
@enderror
<button type="submit">Submit</button>
</form>
Both @error('category_slug') and @enderror('category_slug') directives accomplish the same task of displaying the validation error message for the category_slug field.
By using the @error and @enderror directives, you can easily display validation error messages next to the corresponding input fields in your Laravel Blade templates.
<div class="col-md-4">
<label for="category_slug" class="text-black">{{ __('backend.category.slug') }}</label>
<input id="category_slug" type="text" class="form-control @error('category_slug') is-invalid @enderror" name="category_slug" value="{{ old('category_slug') }}">
<small class="text-muted">
{{ __('categories.category-slug-help') }}
</small>
@error('category_slug')
<span class="invalid-tooltip">
<strong>{{ $message }}</strong>
</span>
@enderror
</div>
Output
Top comments (0)