I have a very strange bug.
Running Laravel 4.1 as my company hasn't upgraded their PHP version yet.
The routes file has this:
Route::controller('survey', 'SurveyController');
And, when you go to /survey/new-survey it ends up being sent to postNewQuestion function instead of postNewSurvey.
public function postNewSurvey() {
$input = Input::all();
//dd($input);
$rules = array(
'name' => 'required|unique:lime_surveys_languagesettings,surveyls_title',
'language' => 'required'
);
...... etc
}
public function postNewQuestion() {
$input = Input::all();
//dd($input);
$rules = array(
'sid' => 'required',
'gid' => 'required',
'type' => 'required',
'question' => 'required',
'mandatory' => 'required',
);
$validator = Validator::make($input, $rules);
if($validator->fails()) {
return Response::json(array('success' => false, 'error' => 'validation',
'messages' => $validator->messages(), 'failed' => $validator->failed()));
}
......... etc
}
Thanks.
Related
I have the method store() to create a new registration type for the conference. But it appears an error "BadMethodCallException
Method [validateEquired] does not exist." in the file "Illuminate/Validation/Validator.php".
Do you know why?
public function store(Request $request, $id)
{
$rules = [
'registration_type_name' => 'required',
'registration_type_capacity' => 'required|integer|min:0',
'registration_type_price' => 'required|integer|min:0',
'registration_type_minimum' => 'equired|integer|min:1',
'registration_type_maximum' => 'rgt:registration_type_minimum|required|integer|min:1',
];
$customMessages = [
'registration_type_name.required' => 'The field name is rqeuired.',
'registration_type_capacity.integer' => 'The field capacity needs to be a positive integer.',
....
];
$this->validate($request, $rules, $customMessages);
$conference = Conference::find($id);
RegistrationType::create([
'name' => $request->registration_type_name,
'description' => $request->registration_type_description,
'capacity' => $request->registration_type_capacity,
'price' => $request->registration_type_price,
'min_participants' => $request->registration_type_minimum,
'max_participants' => $request->registration_type_maximum,
'conference_id' => $conference->id
]);
Session::flash('success', 'Registration type created.');
return redirect()->back();
}
You're missing an r here:
'registration_type_minimum' => 'equired|integer|min:1',
^
I don't know how to get the query string array to validate in Laravel Validation.
here is my code
public function addUserByAdmin(Request $request){
$this->validate($request,[
'name' => 'required',
'fullname' => 'required',
'password' => 'required',
'position' => 'required',
'phone' => 'required'
]);
$uesrAction = new UserAction($this->repository);
$user = $uesrAction->addUser($request->input('phone'),$request->input('password'),$request->input('name'),$request->input('fullname'),$request->input('position'));
if($user){
return response()->json(['success' => 'success','user'=>$user]);
}
return response()->json(['success' => 'fail']);
}
but validation doesn't work.Then I tried Validation::make() method and also didn't work.
My URL be like
http://localhost:8000/admin/users/add-user?phone=abcdefg&password=erer&name=ere&fullname=rere&position=343
If you are using laravel 5.5, change your code as follows:
public function addUserByAdmin(Request $request){
$validatedData = $request->validate([
'name' => 'required',
'fullname' => 'required',
'password' => 'required',
'position' => 'required',
'phone' => 'required'
]);
// ...
}
One of the features that was added in this update is that other way to use the validate() method:
More info:
https://laravel.com/docs/5.5/validation#quick-writing-the-validation-logic
https://laravel.com/docs/5.5/releases
I'm trying to figure out how to pass back to my ajax call that there were validation errors if there is so that I can prevent the page from continuing on and display those errors to the user.
/*
* Create User After they complete the first part of the form.
*
*/
public function createUserAndOrder(Request $request)
{
$validation = $this->validate($request, [
'first_name' => 'required',
'last_name' => 'required',
'email' => 'required|confirmed|unique:users,email',
'email_confirmation' => 'required'
]);
$credentials = [
'first_name' => $request->input('first_name'),
'last_name' => $request->input('last_name'),
'email' => $request->input('email'),
'password' => Hash::make(str_random(8)),
];
$user = Sentinel::registerAndActivate($credentials);
$user->role()->attach(5);
return response()->json([
'success' => true,
'errors' => null
]);
}
You can try it by using Validate Facade as:
$validator = \Validator::make($request->all(), [
'first_name' => 'required',
'last_name' => 'required',
'email' => 'required|confirmed|unique:users,email',
'email_confirmation' => 'required'
]);
// Validate the input and return correct response
if ($validator->fails())
{
return response()->json(array(
'success' => false,
'errors' => $validator->getMessageBag()->toArray()
), 422);
}
This would give you a JSON response like this:
{
'success': false,
'errors': {
'first_name': [
'The first name field is required.'
],
'last_name': [
'The last name field is required.'
]
}
}
I'm using laravel 5.2 and i'm using Form Request that given by laravel vendor to make my code clean, so i don't have many code on my controller :
public function store( CouponRequest $request )
{
DB::beginTransaction();
try {
$coupon = Coupon::create( $request->all() );
DB::commit();
return redirect()->route('admin.coupons.index');
} catch (\Exception $e) {
DB::rollback();
return redirect()->back()->withInput();
}
And this is my sample code about my request form :
public function rules()
{
switch ( strtolower( $this->method ) ) {
case 'post':
{
return [
'code' => 'required|unique:coupons,code',
'name' => 'required',
'start_year' => 'required',
'start_month' => 'required',
'start_day' => 'required',
'start_time' => 'required',
'finish_year' => 'required',
'finish_month' => 'required',
'finish_day' => 'required',
'finish_time' => 'required',
'using_time' => 'required',
'type' => 'required',
'free_shipment' => 'required',
'target' => 'required',
'target_user' => 'required'
];
}
case 'put':
{
return [
'code' => 'required',
'name' => 'required',
'start_year' => 'required',
'start_month' => 'required',
'start_day' => 'required',
'start_time' => 'required',
'finish_year' => 'required',
'finish_month' => 'required',
'finish_day' => 'required',
'finish_time' => 'required',
'using_time' => 'required',
'type' => 'required',
'free_shipment' => 'required',
'target' => 'required',
'target_user' => 'required'
];
}
default:
{
return [];
}
}
}
Where should i place this command? :
$start_date = Carbon::create( $request->start_year, $request->start_month, $request->start_day );
$start_date->setTimeFromTimeString( $request->start_time );
$finish_date = Carbon::create( $request->finish_year, $request->finish_month, $request->finish_day );
$finish_date->setTimeFromTimeString( $request->finish_time );
If i place this code before validation, i could be error when some field not filled well by users.
So what i want is to place this code after validation success, but i don't want to place it at my controller.
Is there FormRequest function that can be called after validation success to modify my request??
I think it's not good when there's much code at controller, so i want to minimalize my controller code.
I am going to attempt this using FormRequest. If the intention here is to both validate and assign start_date and finish_date, this is probably the plausible way of doing so in Laravel:
public function rules()
{
switch ( strtolower( $this->method ) ) {
case 'post':
{
return [
'code' => 'required|unique:coupons,code',
'name' => 'required',
'start_year' => 'required',
'start_month' => 'required',
'start_day' => 'required',
'start_time' => 'required',
'finish_year' => 'required',
'finish_month' => 'required',
'finish_day' => 'required',
'finish_time' => 'required',
'using_time' => 'required',
'type' => 'required',
'free_shipment' => 'required',
'target' => 'required',
'target_user' => 'required'
];
}
case 'put':
{
return [
'code' => 'required',
'name' => 'required',
'start_year' => 'required',
'start_month' => 'required',
'start_day' => 'required',
'start_time' => 'required',
'finish_year' => 'required',
'finish_month' => 'required',
'finish_day' => 'required',
'finish_time' => 'required',
'using_time' => 'required',
'type' => 'required',
'free_shipment' => 'required',
'target' => 'required',
'target_user' => 'required'
];
}
default:
{
return [];
}
}
}
/**
* #inheritDoc
*
* This method overrides Laravel's defeault FormRequest
* to create validator with `after()` hook
*/
protected function validator($validator)
{
$validator
->make(
$this->validationData(), $this->rules(), $this->messages(), $this->attributes()
)
->after(function($validator) {
if ($date = $this->getCarbonInstanceFromPrefix('start')) {
$request->start_date = $date;
} else {
$validator->errors()
->add('start_year', 'Invalid starting date and time');
}
if ($date = $this->getCarbonInstanceFromPrefix('finish')) {
$request->finish_year = $date;
} else {
$validator->errors()
->add('finish_year', 'Invalid finish date and time');
}
});
}
/**
* Retrieve carbon instance from current request, using prefix
*
* #param string $prefix
*
* #return Carbon|null
*/
protected function getCarbonInstanceFromPrefix($prefix = '')
{
try {
$date = Carbon::create(
$request->get($prefix . '_year'),
$request->get($prefix . '_month'),
$request->get($prefix . '_day')
);
$date->setTimeFromTimeString( $request->get($prefix . '_time') );
return $date;
} catch (\Exception $e) {
return null;
}
}
Quick Explanation
FormRequest essentially extends from Illuminate\Foundation\Http\FormRequest and can override the method where instance of Validator is created. By creating your custom validator, you can attach after() event to both validate each date inputs, and also assign additional parameter to request in one go.
I'm using form requests class. Work fine:
class EventFormRequest extends FormRequest
{
public function rules()
{
return [
'event' => 'required|min:10|max:255',
'event_description' => 'required|min:3|max:255',
'url' => 'url',
'date' => 'required|date',
'start_time' => 'required',
'location.street' => 'required|max:255',
'location.house_number' => 'required|min:1|max:5',
'location.place' => 'required|max:255'
];
}
}
But now, I have to add complexer rules, such as combined with Validator. Below the new rules() method of my EventFormRequest class:
public function rules()
{
$v = \Validator::make($this->request->all(),
[
'event' => 'required|min:10|max:255',
'event_description' => 'required|min:3|max:255',
'url' => 'url',
'date' => 'required|date',
'start_time' => 'required',
'location.street' => 'required|max:255',
'location.house_number' => 'required|min:1|max:5',
'location.place' => 'required|max:255'
]);
$v->sometimes('category_id', 'required|numeric', function($input) {
return $input->event_type == 'known';
});
return ($v->fails() ? $v->messages() : []); // validator validates the rules, but returns the messages
}
You see, category_id is required if the event type is 'known'. In the form request rules() method, I cannot return the applied rules as array (see example 1) from the validator, but only the messages().
I'm inspired from here: http://laravel.com/docs/5.1/validation#conditionally-adding-rules
class EventFormRequest extends FormRequest
{
public function rules()
{
$rules = [
'event' => 'required|min:10|max:255',
'event_description' => 'required|min:3|max:255',
'url' => 'url',
'date' => 'required|date',
'start_time' => 'required',
'location.street' => 'required|max:255',
'location.house_number' => 'required|min:1|max:5',
'location.place' => 'required|max:255'
];
if ($this->request->get('event_type') == 'known') {
$rules['category_id'] = 'required|numeric';
}
return $rules;
}
}