how to return validation error in laravel code example
Example 1: if any error in blade laravel
@if ($errors->any())
@foreach ($errors->all() as $error)
<div>{{$error}}</div>
@endforeach
@endif
Example 2: laravel return validation errors
@if($errors->any())
@foreach ($errors->all() as $error)
<div>{{ $error }}</div>
@endforeach
@endif
Example 3: laravel validation types
# <values> = foo,bar,...
# <field> = array field
# <characters> = amount of characters
# accepted # active_url
# after:<tomorrow> # after_or_equal:<tomorrow>
# alpha # alpha_dash
# alpha_num # array
# bail # before:<today>
# before_or_equal:<today> # between:min,max
# boolean # confirmed
# date # date_equals:<today>
# date_format:<format> # different:<name>
# digits:<value> # digits_between:min,max
# dimensions:<min/max_with> # distinct
# email # ends_with:<values>
# exclude_if:<field>,<value> # exclude_unless:<field>,<value>
# exists:<table>,<column> # file
# filled # gt:<field>
# gte:<field> # image
# in:<values> # in_array:<field>
# integer # ip
# ipv4 # ipv6
# json # lt:<field>
# lte:<field> # max:<value>
# mimetypes:video/avi,... # mimes:jpeg,bmp,png
# min:<value> # not_in:<values>
# not_regex:<pattern> # nullable
# numeric # password:<auth guard>
# present # regex:<pattern>
# required # required_if:<field>,<value>
# required_unless:<field>,<value> # required_with:<fields>
# required_with_all:<fields> # required_without:<fields>
# required_without_all:<fields> # same:<field>
# size:<characters> # starts_with:<values>
# string # timezone
# unique:<table>,<column> # url
# uuid
Example 4: rule::exists with custom message laravel
$messsages = array(
'email.required'=>'You cant leave Email field empty',
'name.required'=>'You cant leave name field empty',
'name.min'=>'The field has to be :min chars long',
);
$rules = array(
'email'=>'required|unique:content',
'name'=>'required|min:3',
);
$validator = Validator::make(Input::all(), $rules,$messsages);
Example 5: add error to laravel validation
//setup Validator and passing request data and rules
$validator = \Validator::make(request()->all(), [
'due_date' => 'required',
'template' => 'required'
]);
//hook to add additional rules by calling the ->after method
$validator->after(function ($validator) {
if (request('event') == null) {
//add custom error to the Validator
$validator->errors()->add('event', 'Please select an event');
}
});
//run validation which will redirect on failure
$validator->validate();
//https://dcblog.dev/laravel-adding-custom-validation-errors
Example 6: laravel validation
use Illuminate\Validation\Rule;
Validator::make($data, [
'email' => [
'required',
Rule::unique('users')->ignore($user->id),
],
]);