Working on a Laravel application whereby am working on the backend validation of two dates. The 2 dates are mainly departureDate and returnDate respectively.
On the departure date am trying to validate it to be required, should be of type date and should be a date after today. On the return date I am also trying to implement a validation logic whereby return date should be 3 days or more after departure date but it should be less than 180 days after departure date.
Validate function
public function validateDates(Request $request){
//dd($request->all());
$now = new \DateTime();
$after_date = $now->parse($this->departureDate)->addDays(3);
$maxdays = $now->parse($this->departureDate)->addDays(180);
$validation = $this->validate($request, [
'departureDate' => 'required|date|after:now',
'returnDate' => 'required|date_format:"Y-m-d"|after:' . $after_date->toDateString().'|before:' . $maxdays->toDateString()
],
[
'departureDate.after' => 'Your departure date should be tomorrow or any date in the future',
'returnDate.after' => 'Your return date should be 3 or more days after the departure date',
'returnDate.before' => 'Your return date should be no more than 180 days from the departure date',
]
};
I think your logic is fine. You are, however, probably looking to use Carbon instead. It has the parse() method you are looking for. Also addDays() and toDateString().
So, on top of your file, add the following statement:
use Carbon\Carbon;
and then change your validateDate() method to this one:
public function validateDates(Request $request)
{
$after_date = Carbon::parse($this->departureDate)->addDays(3)->toDateString();
$max_days = Carbon::parse($this->departureDate)->addDays(180)->toDateString();
$validation = $this->validate($request,
[
'departureDate' => 'required|date|after:now',
'returnDate' => 'required|date_format:"Y-m-d"|after:' . $after_date . '|before:' . $max_days
],
[
'departureDate.after' => 'Your departure date should be tomorrow or any date in the future',
'returnDate.after' => 'Your return date should be 3 or more days after the departure date',
'returnDate.before' => 'Your return date should be no more than 180 days from the departure date',
]
);
};
I am assuming that you have your departureDate defined somewhere and hence you are using $this->departureDate, but if it's coming from your request instead, you should change that to $request->departureDate for example.
Related
I'm trying to get all the reservations in a specific date and time and count the guests to find the available seats
What i'm doing in the controller:
public function getSeats() {
$data = request()->validate([
'date' => 'required',
'hours' => 'required',
'place_id' => 'required'
]);
$hours = [];
foreach($data['hours'] as $h) {
$date = $data['date'].' '.$h;
//Carbon date: 2021-08-31 08:00:00 | Database Date: 2021-08-31 08:00:00
$count = Reservation::where('place_id', $data['place_id'])->whereDate('date', Carbon::create($date)->toDateTimeString())->sum('guests');
$object = (object) [
'hour' => $h,
'guests' => $count
];
array_push($hours, $object);
}
}
It returns null, what am i doing wrong?
**Edit
I'm also using 24H in the time selector, so when i create a reservation at 12:00 in the morning eloquent grabs it as 00:00 in the night.
Using where instead of whereDate fixed the issue
I have a date of birth , and I will wish to do 2 things:
1) When, the use enters a date of birth, tha date should be coherent...
For example, if I enter, 2030-10-10, I must have an error message because the date is not coherent. Idem, if I enter 1947-10-10.
2) Is it possible to set the minimum age to be 18 years old?
In my model I have this:
protected $fillable = ['name_mark', 'dateofbirth', 'date_register'];
protected $dates = ['dateofbirth', 'date_register'];
In my Controller I have this:
public function store(Request $request)
{
$request->validate([
'name_mark' => 'required|min:3',
'dateofbirth' => 'required|date',
'date_register' => 'required|date'
]);
Mark::create($request->all());
flashy('Valider');
return redirect()->route('marks.index')
->with('success', 'save');
}
I am yet novice, I thank you for your help and explanation.
You can try using:
before:'.\Carbon\Carbon::now().'|before:18 years ago|
Or:
before:'.Carbon::now().'|before:'.Carbon::now()->subYears(13).'
This works for me, hope it will help you
You can try this:
'dateofbirth' => 'required|date|after:' . $date,
I have an issue with validation by two columns in laravel
I have table work_hours with user_id and date and hours and I have more than one user so I need to give user opportunities to add his hours but only once for a specific date for example
Add 8 hours on 28-03-2018 for user_id = 9, but only once so If user try add once again Add 8 hours on 28-03-2018 for user_id = 9 He has information this date has already taken.
I wrote validation:
$validator = Validator::make($request->all(), [
'date' => 'unique:work_hours',
'name_of_hours' => 'required',
]);
but this work that if somebody of users Add 8 hours on 28-03-2018 for user_id = 9, user_id=10 or another can't add hours on this same date.
So, I need validation for two columns at once, user_id and date but I don't know how to do it.
This sounds like a good case for closures.
$validator = Validator::make($request->all(), [
'date' => function ($attribute, $value, $fail) {
// check the table for the date and current user
$date = DB::table('work_hours')->where([
['date', $value],
['user_id', Auth::user()->id]
])->first();
// if it exists then you fail
if ($date) $fail($attribute.' is invalid.');
},
'name_of_hours' => 'required',
]);
You can review the documentation here: https://laravel.com/docs/5.8/validation#using-closures
I have the following code in my controller..I want to find the difference between two dates(from and to) so that I get the number of days in between the n save it to a database..
class LeaveController extends Controller
{
public function ApplyLeave(Request $request){
$days = $request->datepicker->diff($request->datepicker1);
Auth::user()->sent()->create([
'tel' => $request->tel,
'email' => $request->email,
'start' => Carbon::parse($request->datepicker),
'end' => Carbon::parse($request->datepicker1),
'supervisor' => $request->supervisor,
'department' => $request->department,
'name' => $request->name,
'adress' => $request->adress,
'days' => $days,
]);
return view('home');
}
with what I have so far , I get the following error:
Call to a member function diff() on string
How to go about with this?
Man, Don't use Carbon when basic PHP functions can provide you the best solution. Use OOP:
$datetime1 = new DateTime($request->datepicker);
$datetime2 = new DateTime($request->datepicker1);
$interval= $datetime1->diff($datetime2);
$days = $interval->format('%a');
If you are curious why you are getting that error then its because you are using diff() function which takes date object as parameter and you are providing plain string.
You need to:
$d1 = new Carbon($request->datepicker);
$d2 = new Carbon($request->datepicker1);
$days = $d1->diff($d2)->days;
Note that you need ->days to get the actual days amount.
Note that you will have trouble with times. You may wish to ->setTime(0,0,0) in order to get the days between 2 dates.
Note that your format may not be standard. In this case use:
$format = 'm\d\Y';
$d1 = Carbon::createFromFormat($request->datepicker,$format);
$d2 = Carbon::createFromFormat($request->datepicker1,$format);
$days = $d1->diff($d2)->days;
I want to compare two date in validation. I mean the user will input start date and end date .I want to verify the start date, it can't be yesterday . And end date will not be before day of start date. Please guide me in laravel validation.
I would suggest you to make your custom validation for dates,
Place the following function in your App\Providers\ValidationServiceProvider class boot() method
//end date must be equal to value or greate than value
Validator::extend('dateequalorearlier', function($attribute, $value, $parameters, $validator) {
$date_compare = array_get($validator->getData(), $parameters[0]);
return Carbon::parse($date_compare) >= Carbon::parse($value);
});
//end date must be greater
Validator::extend('dateearlier', function($attribute, $value, $parameters, $validator) {
$date_compare = array_get($validator->getData(), $parameters[0]);
return Carbon::parse($date_compare) > Carbon::parse($value);
});
//start time must be earlier
Validator::extend('earliertime', function($attribute, $value, $parameters, $validator) {
$time_compare = array_get($validator->getData(), $parameters[0]);
return Carbon::parse($time_compare) > Carbon::parse($value);
});
There are three new custom validation I have defined, one is for date equal or earlier, second one is for date earlier and third one is for earlier time incase you need time validation, if not necessary just remove those .
You must place appropriate error message in your Language validation file, find it in resources\lang\validation.php.
'dateequalorearlier' => 'The Start date must be an earlier date or Same date from End date',
'dateearlier' => 'The Start date must be an earlier date from End date',
'earliertime' => 'The Start time must be an earlier time from End time',
and you can then use the custom validation where ever you want as in the following code snippet.
$rules = [
'start_date' => 'required|date|dateequalorearlier:end_date',
'end_date' => 'required|date',
];
$messages = [
'start_date.required' => 'Start date is a required field.',
'start_date.date' => 'Start date must be in a valid date format (YYYY-MM-DD).',
'start_date.dateequalorearlier' => 'Start date must be an earlier date or Same date from End date.',
'end_date.required' => 'End date is a required field.',
'end_date.date' => 'End date must be in a valid date format (YYYY-MM-DD).',
];
$validator = Validator::make($request->all(),$rules,$messages);
if($validator->fails()){
$this->throwValidationException($request,$validator);
}
make sure you have included validator facade where ever you are doing validation..
use Illuminate\Support\Facades\Validator;