validate end date using start date in laravel 5 using request class - laravel-5

This is my request class.
public function rules()
{
$input = Input::all();
return [
'title' => 'required|unique:event_cals,title',
'eventDate' => 'required|date|after:yesterday',
'endDate' => 'date|before:event_cals,' . date( 'Y-m-d', strtotime( $input['eventDate'] . ' +1 day' ) ),
'venue' => 'required',
'time' => 'required',
'type' => 'required',
'photo' => 'mimes:jpeg,bmp,png,jpg|max:1000'
];
}
public function messages(){
return [
'title.required' => 'Title is required.',
'title.unique' => 'Title is already there.',
'eventDate.after' => 'Event Date is passed.',
'eventDate.required' => 'Event Date is required.',
'venue.required' => 'Venue is required.',
'time.required' => 'Time is required.',
'type.required' => 'Type is required.',
'endDate.date' => 'Due Date should be after starting date',
];
}
There I want to verify whether endDate is after the eventDate. It is working properly except when endDate is similar to eventDate. But I want to make sure that there must be able to add an endDate which is similar to eventDate also. For an example if the eventDate is 03/04/2016, there can be able to add an endDate as 03/04/2016 or any upcoming date. But from above rule 03/04/2016 is invalid as an endDate. Is there any keyword for before or equal? Please can any one help me figure out this mess?

Assuming you are getting the input before you establish the $rules, you can try adding one day to eventDate before validation:
$rules = [
'eventDate' => 'required|date|after:yesterday',
'endDate' => 'date|before:event_cals,' . date( 'Y-m-d', strtotime( $input['eventDate'] . ' +1 day' ) ),
];
Or you can extend Laravel to create a new validation rule that handles this for you (and makes it easier to reuse in other controllers).

Related

Show validation messages in laravel

I wrote this code for storing products :
public function rules()
{
return [
'trans_data.*.name' => 'required', //translation data
'trans_data.*.description' => 'required',
'url' => 'required',
'action' => 'required',
];
}
'*' is for lots of languages and we have 5 languages , I wrote this code for error message but I think it needs refactor.
public function messages()
{
return [
'trans_data.en.name.required' => 'English name is required',
'trans_data.nl.name.required' => 'Dutch name is required',
'trans_data.en.description.required' => 'English description is required',
'trans_data.nl.description.required' => 'Dutch description is required'
.
.
.
];
}
I want to summarize these lines, and languages be dynamic like :
:attribute name is required
Is it possible?

Laravel: conditional validation rules

In my laravel application I need to apply the validation rules on conditional bases. For example: In the Store method the password field is required and min chars: 6. But, in Update method password field is not required, however, if the user enters the password then it must be greater than 6 chars.
SomeController.php
private function validations($customRules = [])
{
# variables
$rules = [
'contact_person' => 'required|min:2',
'mobile_number' => 'required|numeric',
'pword' => 'required|min:6',
'email' => 'required|email',
'address' => 'required',
'status' => 'required',
];
$messages = [
'contact_person.required' => '`<strong class="style-underline">Contact person</strong>` - Required',
'contact_person.min' => '`<strong class="style-underline">Contact person</strong>` - Must be at least :min chars',
'mobile_number.required' => '`<strong class="style-underline">Mobile number</strong>` - Required',
'mobile_number.numeric' => '`<strong class="style-underline">Mobile number</strong>` - Must be a numeric value',
'email.required' => '`<strong class="style-underline">Eamil</strong>` - Required',
'email.email' => '`<strong class="style-underline">Email</strong>` - Must be a valid email address',
'pword.required' => '`<strong class="style-underline">Password</strong>` - Required',
'pword.min' => '`<strong class="style-underline">Password</strong>` - Must have a at least :min characters',
'status.required' => '`<strong class="style-underline">Status</strong>` - Required',
];
if(!empty($customRules))
$rules = \array_merge($rules, $customRules);
# returning
return request()->validate($rules, $messages);
}
After modifying the rules, based on the update method requirement, the pword field is validated for min chars. Which should not happen as the field was left empty.
Currently I am forced to do this.
public function update()
{
...
# validating submitted data
if(!empty(request()->pword))
$this->validations([ 'pword' => 'min:6' ]);
else
$this->validations([ 'pword' => '' ]);
....
}
You can use nullabe instead required, Blank value converted as null if you are using eloquent, because of below middleware
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
So your method would be like
private function validations($request,$update = false){
$rules = [
'contact_person' => 'required|min:2',
'mobile_number' => 'required|numeric',
'pword' => 'nullable|min:6',
'email' => 'required|email',
'address' => 'required',
'status' => 'required',
];
}

How to check year in date validation rule in Laravel

In Laravel, I have a Convention object with year, start_date and end_date. The constrain is that the start_date and end_date fields belong to the year field.
I wanna use a request validation, but none of the available rule seem to correspond to my need.
I would like something like this (but it does not work):
class ConventionRequest extends FormRequest
{
public function rules() {
return [
'year' => 'required',
'start_date' => 'required|date|after_or_equal:year-01-01',
'end_date' => 'required|date|before_or_equal:year-12-31']
}
}
Make a custom Rule:
//YearIsGreater Rule class
public function passes($attribute, $value)
{
$date = DateTime::createFromFormat("Y-m-d", $value);
$year = $date->format("Y");
return $year > request('year');
}
and use it like that
return [
'year' => 'required',
'start_date' => [
'required',
'date',
new YearIsGreater,
],
//
],
Thanks for your responses. Actually, I succeeded in my initial research direction:
$SameYear = "|after_or_equal:" . $this->year . "-01-01|before_or_equal:" . $this->year . '-12-31' ;
return [
'year' => 'required',
'start_date' => 'required|date' . $SameYear,

Validate whether multiple fields are unique simultaneously in laravel 5

This my request class rules.
return [
'title' => 'required|unique:event_cals,title',
'eventDate' => 'required|date|after:yesterday',
'venue' => 'required',
'time' => 'required',
'type' => 'required',
'unique:event_cals,eventDate,NULL,id,venue,$request->venue,time,$request->time'
];
I want to validate a rule like below.
'eventDate' && 'venue' && 'time' => 'unique'
There I need to check if there any row without same eventDate, venue and time altogether. Anyone knows how to declare such a rule?
This is the snapshot of db table.
Here is the possible solution:
<?php
return [
'title' => 'required|unique:event_cals,title',
'eventDate' => 'required|date|after:yesterday',
'venue' => 'required',
'time' => 'required',
'type' => 'required',
'event_date' => "unique:event_cals,event_date,NULL,id,venue,{$request->venue},time,{$request->time}",
];
I again want to highlight that; if you want that validator to work, you should make sure that the event_date and time should be correctly formatted.
An example unique check with additional wheres from our running project's update requests:
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
$id = $this->route('money');
return $rules = [
'name' => "required|string|min:3|max:255|unique:moneys,name,{$id},id,deleted_at,NULL,access,public",
];
}

Combining validation syntax in CakePHP

Say I have a fairly typical, by-the-docs validation array and I want to keep those rules and add a specific validation rule for 8+ other fields.
Original $validate:
var $validate = array(
'name' => array(
'notEmpty'=> array(
'rule' => 'notEmpty',
'message' => 'Name can not be blank.'
),
'allowedCharacters'=> array(
'rule' => '|^[a-zA-Z ]*$|',
'message' => 'Name can only be letters.'
),
'minLength'=> array(
'rule' => array('minLength', 3),
'message' => 'Name must be at least 3 characters long.'
),
'maxLength'=> array(
'rule' => array('maxLength', 255),
'message' => 'Name can not be longer that 255 characters.'
)
),
'email' => array(
'email' => array(
'rule' => 'email',
'message' => 'Please provide a valid email address.'
),
'isUnique' => array(
'rule' => 'isUnique',
'message' => 'This E-mail used by another user.'
)
)
);
I can add the following rule to the validation array, but I do not want to have to repeat it 8 times.
////fragment of array
'field1' => array(
'greaterThanField' => array(
'rule' => array('greaterThanField', 'age'),
'message' => 'This field cannot be greater than age'
)
)
////
function greaterThanField( $field=array(), $compare_field=null ){
foreach( $field as $key => $value ){
$v1 = $value;
$v2 = $this->data[$this->name][ $compare_field ];
if($v1 > $v2) {
return false;
} else {
continue;
}
}
return true;
}
And I want to add to this an array of field names that will all be evaluated using the same rule and message. I tried creating a variable in the model and then running code on the beforeValidate function, but beforeValidate doesn't seem to have access to the compareFields variable
var $compareFields = array('field1', 'field2', 'field3', 'field4', 'field5', 'field6', 'field7', 'field8');
function beforeValidate(){
foreach ($compareFields as $field) {
$validate[$field] = array(
'rule'=> array('greaterThanField', 'age' ),
'message'=>'Cannot exceed delivery age',
);
}
}
What is the proper way to achieve this?
If you're using 2.2 then check this.
If you're using an older version and (if I understood correctly your question) you are too lazy to add the same validation rule to multiple fields, then I would add them dynamically in the constructor of your model. I don't like that solution though, I would stick to the convention.

Resources