Laravel 5.2 Validation not working - php

I have following forms
{{ Form::text("theme[header_color]", '', []) }}
{{ Form::text("theme[bg_color]", '', []) }}
{{ Form::text("theme[text_color]", '', []) }}
I added following rules in request method.
theme[text_color]="required",
theme[bg_color]="required",
theme[text_color]="required"
I enter value in all field but still getting required validation error.
Please help have a look and help us.
THanks

Try this code does this help
$rules = array(
'theme.text_color' => 'required',
'theme.bg_color' => 'required',
'theme.header_color' => 'required',
);
$messages = [
'theme.text_color.required' => 'Please add Text Color.',
'theme.bg_color.required' => 'Please add Text Color.',
'theme.header_color.required' => 'Please add Header Color.',
];

Related

How to return custom error message from controller method validation

How to return a custom error message using this format?
$this->validate($request, [
'thing' => 'required'
]);
to get custom error message you need to pass custom error message on third parameter,like that
$this->validate(
$request,
['thing' => 'required'],
['thing.required' => 'this is my custom error message for required']
);
For Multiple Field, Role and Field-Role Specific Message
$this->validate(
$request,
[
'uEmail' => 'required|unique:members',
'uPassword' => 'required|min:8'
],
[
'uEmail.required' => 'Please Provide Your Email Address For Better Communication, Thank You.',
'uEmail.unique' => 'Sorry, This Email Address Is Already Used By Another User. Please Try With Different One, Thank You.',
'uPassword.required' => 'Password Is Required For Your Information Safety, Thank You.',
'uPassword.min' => 'Password Length Should Be More Than 8 Character Or Digit Or Mix, Thank You.',
]
);
https://laravel.com/docs/5.3/validation#working-with-error-messages
$messages = [
'required' => 'The :attribute field is required.',
];
$validator = Validator::make($input, $rules, $messages);
"In most cases, you will probably specify your custom messages in a language file instead of passing them directly to the Validator. To do so, add your messages to custom array in the resources/lang/xx/validation.php language file."
Strangely not present in the documentation, you can specify the first parameter as the validation rules & the second parameter as the message format directly off of the Illuminate/Http/Request instead of invoking $this or the Validator class.
public function createCustomer(Request $request)
{
# Let's assume you have a $request->input('customer') parameter POSTed.
$request->validate([
'customer.name' => 'required|max:255',
'customer.email' => 'required|email|unique:customers,email',
'customer.mobile' => 'required|unique:customers,mobile',
], [
'customer.name.required' => 'A customer name is required.',
'customer.email.required' => 'A customer email is required',
'customer.email.email' => 'Please specify a real email',
'customer.email.unique' => 'You have a customer with that email.',
'customer.mobile.required' => 'A mobile number is required.',
'customer.mobile.unique' => 'You have a customer with that mobile.',
]);
}
You need to first add following lines in view page where you want to show the Error message:
<div class="row">
<div class="col-md-4 col-md-offset-4 error">
<ul>
#foreach($errors->all() as $error)
<li>{{$error}}</li>
#endforeach
</ul>
</div>
</div>
Here is a demo controller by which error message will appear on that page:
public function saveUser(Request $request)
{
$this->validate($request,[
'name' => 'required',
'email' => 'required|unique:users',
]);
$user=new User();
$user->name= $request->Input(['name']);
$user->email=$request->Input(['email']);
$user->save();
return redirect('getUser');
}
For details You can follow the Blog post.
Besides that you can follow laravel official doc as well Validation.

Store an array of elements to database (Laravel)

I need advice how to store an array to database. For example i have an input with name="user_phone[]" and i want to store to database the value of this input.
I have a form like so, also there other inputs but i copy just one:
{!! Form::open([route('some.router')]) !!}
<fieldset class="form-group">
{{ Form::label(null, 'Phone') }}
{{ Form::text('user_phone[]', null, ['class' => 'form-control'] ) }}
</fieldset>
{!! Form::close() !!}
and the controller:
public function postAddOrder(Request $request)
{
$this->validate($request, [
'receipt_date' => 'date|required',
'return_date' => 'date|required',
'user_name' => 'required',
'user_phone' => 'required',
'work_sum' => 'integer|required',
'user_descr' => 'required',
'foruser_descr' => 'required'
]);
$user = new User;
$user = $user->all()->find($request->input('user_name'));
$order = new Order([
'receipt_date' => $request->input('receipt_date'),
'return_date' => $request->input('return_date'),
'user_name' => $user->fio,
'user_phone' => $request->input('user_phone'),
'device' => $request->input('device'),
'work_sum' => $request->input('work_sum'),
'master_name' => $request->input('master_name'),
'user_descr' => $request->input('user_descr'),
'foruser_descr' => $request->input('foruser_descr'),
'type' => $request->input('type'),
'status' => $request->input('status'),
'engineer' => $request->input('engineer'),
'partner' => $request->input('partner'),
'office' => $request->input('office')
]);
$order->save();
return redirect()->route('admin.orders.index');
}
The problem is when i'm submitting the form and getting the error:
htmlentities() expects parameter 1 to be string, array given
Also i'm using casts to store an array to DB:
/**
* The attributes that should be casted to native types.
*
* #var array
*/
protected $casts = [
'user_phone' => 'array',
];
The values are storing correctly, the main problem is that the validate() method is not catching the errors. For example im not filling some data in inputs which are required. When instead of getting the error like something is required im getting error
htmlentities() expects parameter 1 to be string, array given
When im filling all input with data everything goes ok.
I think the problem comes from your rule
'user_phone' => 'required
To validate array values you should use the array validation. (Link)
rewrite your rule like so
"user_phone.0" => "required"
this will ensure that at least one user_phone is provided.
In case you wanna validate phone format just go with:
"user_phone.*" => "{Insert validation here}"
Found the definition.
{!! Form::open([route('some.router')]) !!}
<fieldset class="form-group">
{{ Form::label(null, 'Phone') }}
{{ Form::text('user_phone[0]', null, ['class' => 'form-control'] ) }}
</fieldset>
{!! Form::close() !!}
We must pass the index in inputs. Like name="user_phone[0]" after that we are not getting the error:
htmlentities() expects parameter 1 to be string, array given
And validate() method catching the errors. It was the only solution for me.

Where are Validator error messages stored in Laravel?

I have the following code in a blade file:
#if($errors->has('password_again'))
<div class="error">
* {{ $errors->first('password_again') }}
</div>
#endif
This line:
{{ $errors->first('password_again') }}
Displays:
"The password again field is required."
However I can't seem to find this string anywhere. I've looked in the Controller file which calls this blade and just went through a ton of files searching for the string and can't seem to find it. Which file should I be looking in to edit this string?
EDIT:
I tried this it doesn't seem to do anything?
$messages = [
'password_again' => 'The confirm password field is required.',
];
$validator = Validator::make(Input::all(),
array(
'email' => 'required|max:50|email|unique:users',
'username' => 'required|max:30|min:3|unique:users',
'password' => 'required|min:8',
'password_again' => 'required|same:password'
),
$messages
);
If needed, you may use custom error messages for validation instead of the defaults. There are several ways to specify custom messages.
Passing Custom Messages Into Validator
$messages = [
'required' => 'The :attribute field is required.',
];
$validator = Validator::make($input, $rules, $messages);
Specifying Custom Messages In Language Files
In some cases, you may wish to specify your custom messages in a language file instead of passing them directly to the Validator. To do so, add your messages to custom array in the resources/lang/xx/validation.php language file.
Read more at:
http://laravel.com/docs/5.0/validation

passing two parameter in form cant seem to figue out

Basically I have an event ID and User ID i need to pass in the form to store... however when i hit create it comes up with
Route pattern "/roles/{id}/{{id}}" cannot reference variable name "id" more than once.
However if i hit enter in the URL bar it works... so not to sure whats happening here... help would be greatful here the code.
Route file
// POST Add Users Race
Route::post('racehistory/{event_id}/store/{user_id}/race/', 'racehistoryController#store');
// GET Current Races
Route::get('events/currentRace', 'racingeventController#viewCurrentRace');
// GET Users
Route::get('events/{event_id}/users', 'racingeventController#users');
// GET Users with Group ID
Route::get('events/{event_id}/{group_id}', 'racingeventController#grouped');
// GET Add Users Race Form
Route::get('events/{event_id}/user/{user_id}/addrace', 'racingeventController#addUserRace');
// Add User to Event
Route::get('events/{event_id}/user/{user_id}', 'racingeventController#addUserToEvent');
// DELETE Remove User from Race Event
Route::get('events/{event_id}/delete/user/{user_id}', 'racingeventController#deleteUserToEvent');
// DELETE Race Event
Route::get('events/delete/{event_id}', 'racingeventController#destroy');
Route::resource('events', 'racingeventController');
Form View
{{ Form::open(array('class' => 'form-horizontal', 'method' => 'post', 'action' => array('racehistoryController#store', $user->id, $event->id))) }}
Controller - racehistoryController
public function store($event_id, $user_id)
{
$rules = array(
'start_event' => 'required',
'end_event' => 'required',
'pool_type' => 'required|max:3|min:3',
'name' => 'required|max:35|min:3',
'location' => 'required|max:35|min:3',
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
return 'form works';
}
}
Name your route:
Route::get(
'racehistory/{event_id}/store/{user_id}/race/',
['as' => 'store', 'uses' => 'racehistoryControlle#store']
);
Fix Form::open() helper:
{{
Form::open([
'class' => 'form-horizontal',
'method' => 'post',
'route' => ['store', $user->id, $event->id]
])
}}

Laravel Session Flash persists for 2 requests

Recently I have changed to Laravel from Codeigniter, everything was going fine except I encountered a problem with Session::flash.
when I create new user I get success message but It will persist for 2 requests, even I didn't pass the validator:
my code in UsersController:
function getCreateUser(){
$config = array(
'pageName' => 'createUser',
'pageTitle' => 'Create User',
'formUrl' => action('UsersController#postCreateUser'),
'modelFields' => array(
array('db_name' => 'employee_id', 'text' => 'Employee Id', 'mandatory' => TRUE),
array('db_name' => 'full_name', 'text' => 'Full Name', 'mandatory' => TRUE),
array('db_name' => 'email', 'text' => 'Email', 'mandatory' => FALSE),
array('db_name' => 'password', 'text' => 'Password','value' => '12345', 'mandatory' => TRUE)
),
'submit_text' => 'Create'
);
return View::make('layouts.form', $config);
}
function postCreateUser(){
$config = array(
'pageName' => 'createUser',
'pageTitle' => 'Create User',
'formUrl' => action('UsersController#postCreateUser'),
'modelFields' => array(
array('db_name' => 'employee_id', 'text' => 'Employee Id', 'mandatory' => TRUE),
array('db_name' => 'full_name', 'text' => 'Full Name', 'mandatory' => TRUE),
array('db_name' => 'email', 'text' => 'Email', 'mandatory' => FALSE),
array('db_name' => 'password', 'text' => 'Password','value' => '12345', 'mandatory' => TRUE)
),
'submit_text' => 'Create'
);
$validator = User::validate(Input::all());
if($validator->passes()){
$user = new User(Input::all());
$user->password = Hash::make(Input::get('password'));
$user->Company_id = '1';
$user->save();
Session::flash('message', 'User Created Successfully!');
Session::flash('alert-class', 'alert-success');
return View::make('layouts.form', $config);
}
return View::make('layouts.form', $config)->withErrors($validator->messages());
}
in form.blade:
#if ( $errors->count() > 0 )
<div class="alert alert-danger">
<p>The following errors have occurred:</p>
<ul>
#foreach( $errors->all() as $message )
<li>{{ $message }}</li>
#endforeach
</ul>
</div>
#endif
in master.blade:
#if(Session::has('message'))
<p class="alert {{ Session::get('alert-class', 'alert-info') }} alert-dismissable"> {{ Session::get('message') }}</p>
#endif
Maybe I'm not alone with this issue, here is another unanswered question.
Update
For anyone in future facing this problem:
Never flash session data without redirecting.
My code now looks like this:
function postCreateUser(){
$validator = User::validate(Input::all());
if($validator->passes()){
$user = new User(Input::all());
$user->password = Hash::make(Input::get('password'));
$user->Company_id = '1';
$user->save();
Session::flash('message', 'User Created Successfully!');
Session::flash('alert-class', 'alert-success');
} else {
Session::flash('message', Helpers::formatErrors($validator->messages()->all()));
Session::flash('alert-class', 'alert-danger');
}
return Redirect::action('UsersController#getCreateUser');
}
You are Flashing session data and creating a view instead of redirecting, meaning the message will Flash for this request and for the next one, showing twice.
If you want to show the message on the current request without redirecting, I would suggest providing the errors to your View::make instead of trying to Flash the messages. If you MUST Flash the message on the current request, then you will need to Session::forget('key') or Session::flush() after your view.
The following seems to be available from version 5.1 onward. It used to be undocumented, now it is: see Laravel's session documentation.
session()->now()
This is the same as flash, except it won't persist to the next request.
As #Drew said earlier
You are Flashing session data and creating a view instead of
redirecting, meaning the message will Flash for this request and for
the next one, showing twice.
An easy way to flash a message once when you are creating a view is:
Session::flash($key, $value);
Session::push('flash.old', $key);
Happy coding!
I had a similar problem, but I couldn't use Return::redirct, as I was using Ajax to to post to and from a within a set of Tabs.
Therefore, I was calling
Input::flashExcept('_token');
only if the validation failed and returning a view with the old input. Assuming validation passed and I wanted to run some functions and create a new view based on new data, I would call:
Session::forget('_old_input');
I would put this before my final View::make
Hope this helps (or makes sense)...
create:
$request->session()->flash('status', 'Task was successful!');
delete:
$request->session()->forget('status');
Check the scope of your Api's both session put and session get Api's have to be in same scope(i e web.php or api.php).
A good method to repopulate form with old data:
Controller:
View::make( 'view.name' )->withOldFormData( Input::all() );
View:
{{ Form::model( $old_form_data ) }}

Categories