This question already has answers here:
How to return custom error message from controller method validation
(5 answers)
Closed 4 years ago.
Good day to all, I want to change default error message as "Title is required" to "Please enter title" The code I use:
Controller
$this->validate($request, [
'Title'=>'required',
]);
Also, how can I ensure that a user cannot save the same data into database, for example, if there is already a Title as Movie 43 we do not have to let user save that Title again in the database.
The signature of the validate function is:
public function validate(Request $request, array $rules, array $messages = [], array $customAttributes = [])
You can pass in custom messages as the third parameter. The key of the custom message can be either field_name for all errors relating to that field, or you can be more specific and use field_name.rule. In this case you should use:
$this->validate(
$request,
['Title' => 'required'],
['Title.required' => 'Please enter title']
);
use Validator;
if you have much more validations this could be better
$validator = Validator::make($request->all(), $rules, $messages);
Try this
$rules = [
'Title'=>'required|unique'
];
$messages = [
'Title.required' => 'Please Enter Title',
'Title.unique' => 'Please Enter Unique Title'
];
$validator = Validator::make(Input::all(), $rules, $messages);
And above declaration of controller class
use Validator;
use Illuminate\Support\Facades\Input;
Hope it helps you!
Related
I found difficulties to set custom validation message without making a
request class. That's why I am explaining it for a better
understanding.
Default validation of laravel:
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required|unique:categories',
]);
$input = $request->all();
Category::create($input);
Session::flash('create_category','Category created successfully');
return redirect('admin/categories');
}
It will show the default message of laravel. In this question-answer section I will show how easily I solved this problem with the help of laravel documentation.
you can find other ways of doing this here in laravel documentation.
You have to simply pass the three values to the validate parameter.
Your input as $request
Your rules as $rules
Your custom message as $message
public function store(Request $request)
{
$rules = ['name'=>'required|unique:categories'];
$message = [
'name.required' => 'The category name is required',
'name.unique' => 'Category name should be unique'
];
$this->validate($request, $rules, $message);
$input = $request->all();
Category::create($input);
Session::flash('create_category','Category created successfully');
return redirect('admin/categories');
}
I found that this is the smartest way of doing custom validation without making a request class. If your input field is a few and you want to your validation in the controller then you can do your validation in this way.
Thank's for reading.
I have a page that has a form with a select menu and if there are some validation errors in that form the validation errors are shown using "#include('includes.errors')". But in this same page I have a button that when the user clicks in it it shows a modal where the user can introduce a subject, a message to send an email. In this modal I also have "#include('includes.errors')".
Issue: So the issue is that if there are validation errors in the form in the modal because the subject or messare were not filled by the user that errors appear on the modal but also on the same page above the form that has the select menu. Also if there are some validation errors in the form that has the select menu and the user opens the modal that validation erros also appear in the modal.
To fix this issue using named bags is not working. For example in the storeQuantities() there is:
public function storeQuantities(Request $request, $id, $slug = null)
{
$validator = $request->validate([
'rtypes' => ['required', 'array', new RegistrationTypeQuantity],
]);
// dd('test'); dont shows
if ($validator->fails())
{
return redirect()->back()->withErrors($validator, 'quantitiesError');
}
...
}
In the contactOrganizer:
public function contactOrganizer($id, Request $request)
$validator = $this->validate($request, $rules, $customMessages);
// dd('test'); dont shows
if ($validator->fails())
{
return redirect()->back()->withErrors($validator, 'contactErrors');
}
}
And then use:
#include('includes.errors', ['errors' => $errors->quantitiesError])
And in the modal:
#include('includes.errors', ['errors' => $errors->contactErrors])
But its not working it appears always that the bag is empty in both cases with "{{dump($errors->contactErrors)}}" and "{{dump($errors->quantitiesError)}}" like:
"MessageBag {#336 ▼
#messages: []
#format: ":message"
}"
It seems that the issue is because there is some error in "$validator = $this->validate($request, $rules, $customMessages);", any code after this line like "dd('test);" dont appears.
Laravel will automatically redirect the user back to their previous location when $this->validate is used
You need to use Validator::make instead Manually Creating Validators
$validator = Validator::make($request->all(), [
'rtypes' => ['required', 'array', new RegistrationTypeQuantity],
]);
if ($validator->fails())
// redirect with errors
}
And don't forger to include use Validator;
I'm using Validator to validate the input:
$validator = Validator::make($request->all(), [
'short' => 'required',
'name' => 'required|unique:type_event,name'
]);
if ($validator->fails()) {
// fails validation
}
When the unique check is fired, is there a way to receive the id or the record that already exists into the DB? Or I've to call the Model for example with:
$data = TypeEventModel::where('name', '=', $request->input('name'))->firstOrFail();
Thank you.
First you need a custom validation rule. Add the following code to app/Providers/AppServiceProvider.php in boot() method:
Validator::extend('unique_with_id', function ($attribute, $value, $parameters, $validator) {
// First we query for an entity in given table, where given field equals the request value
$found = DB::table($parameters[0])
->where($parameters[1], $value)
->first();
// then we add custom replacer so that it gives the user a verbose error
$validator->addReplacer('unique_with_id', function ($message, $attribute, $rule, $parameters) use ($found) {
// replace :entity placeholder with singularized table name and :id with duplicate entity's id
return str_replace([':entity', ':id'], [str_singular($parameters[0]), $found->id], $message);
});
// finally return wether the entity was not found (the value IS unique)
return !$found;
});
Then add the following validation message to resources/lang/en/validation.php
'unique_with_id'=>'Same :entity exists with ID :id',
Finally you can use
$validator = Validator::make($request->all(), [
'short' => 'required',
'name' => 'required|unique_with_id:type_event,name'
]);
So, I'm trying to make an e-mail view, using data the user posted. The problem is, that specific data is unreachable. I don't know how I'm supposed to get that data.
Here is my controller:
public function PostSignupForm(Request $request)
{
// Make's messages of faults
$messages = [
//removed them to save space
];
//Validation rules
$rules = [
//removed them to save space
];
$validator = Validator::make($request->all(), $rules, $messages);
if ($validator->fails()) {
return Redirect::back()->withInput()->withErrors($validator);
}
DB::table('rittensport')->insert([
'note' => $request->get('note'),
//standard instert
]);
/**
* Sending the e-mails to the pilot and co-pilot
*
* #return none
*/
Mail::send('emails.rittensport_signup', $request->all(), function ($message) {
$message->from(env('APP_MAIL'), 'RallyPodium & Reporting');
$message->sender(env('APP_MAIL'), 'RallyPodium & Reporting');
$message->to($request->get('piloot_email'), strtoupper($request->get('piloot_lastname')).' '.$request->get('piloot_firstname'));
$message->to($request->get('navigator_email'), strtoupper($request->get('navigator_lastname')).' '.$request->get('navigator_firstname'));
$message->subject('Uw inschrijving voor de RPR Gapersrit '. date('Y'));
$message->priority(1);//Highest priority (5 is lowest).
});
return Redirect::back();
Well, the view exists and the error I'm facing to is:
Undefined variable: request.
This is how I try to get the data in the e-mail view: {{ $request->get('note') }} I already tried things like {{ $message->note }}, $message['note'] And so on.
Try this:
Mail::send('emails.rittensport_signup', array("request" => $request), function (...
I want to validate alpha_dash(Alphabets and Spaces) and the code below works fine
Validator::extend('alpha_spaces', function($attribute, $value)
{
return preg_match("/^[a-z0-9 .\-]+$/i", $value);
});
but the error it gives is not user friendly :
validation.alpha_spaces
How can change this message?
This is the method where it is posts
public function create(Request $request)
{
$this->validate($request, [
'title' => 'required|alpha_spaces|max:255',
]);
}
Thanks!
Just add your custom error message as an array element to resources/lang/xx/validation.php:
'alpha_spaces' => 'The :attribute may only contain letters, numbers and spaces.',
Read more: http://laravel.com/docs/5.0/validation#custom-error-messages