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
Related
I have to update the expiry date by counting from the month. Please guide me. While saving data expiry date is working fine. But I don't understand how to update it.
My Controller Code For Save Data
public function pay_success(Request $request){
$input = $request->all();
date_default_timezone_set('asia/calcutta');
$input['months'] = $request->months;
$expiry_date = Carbon::now()->addMonths($input['months']);
$input['expiry_date'] = $expiry_date;
$input['password'] = bcrypt($input['password']);
$user = User::create($input);
//Send Email
$email = $input['email'];
$messageData = ['email' =>$input['email'],'name' =>$input['name'],'package' =>$input['package'],'months' =>$input['months'],'amount' =>$input['amount'],'expiry_date' =>$input['expiry_date']];
Mail::send('emails.mail',$messageData,function($message) use($email){
$message->to($email)->subject('Registration with AddSpy');
});
$arr = array('msg' => 'Payment successful.', 'status' => true);
return Response()->json($arr);
}
My Update Code is
public function update(Request $request) {
date_default_timezone_set('asia/calcutta');
$months = $request->months;
$expiry_date = Carbon::now()->addMonths($months);
$request['expiry_date'] = $expiry_date;
$data = ['id'=>$request->id, 'name'=>$request->name, 'phone'=>$request->phone, 'country'=>$request->country, 'state'=>$request->state,
'purpose'=>$request->purpose, 'package'=>$request->package, 'months'=>'$months', 'quantity'=>$request->quantity, 'amount'=>$request->amount, 'expiry_date'=>'$expiry_date'];
DB::table('users')->where('id',$request->id)->update($data);
return response()->json($data);
}
Anyone please suggest me a answer. I do changes in my code but It gives this message "message": "SQLSTATE[22007]: Invalid datetime format: 1292 Incorrect date value: '$expiry_date' for column addspy.users.expiry_date at row 1 (SQL: update users set id = 47, name = Ayush, phone = 6393611129, country = India, state = UP, purpose = parent, package = basic, months = $months, quantity = 1, amount = 4000, expiry_date = $expiry_date where id = 47)",
"exception": "Illuminate\Database\QueryException",
Thanks in advance
You're sending strings to the database ('$months' & '$expiry_date'). Simply removing the quotes should fix your problem.
i.e.
$data = [
'id' => $request->id,
'name' => $request->name,
'phone' => $request->phone,
'country' => $request->country,
'state' => $request->state,
'purpose' => $request->purpose,
'package' => $request->package,
'months' => $months,
'quantity' => $request->quantity,
'amount' => $request->amount,
'expiry_date' => $expiry_date,
];
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.
i am trying to figure out how to solve this problem... i have a form with 4 inputs : beginDate, beginHour, endDate, endHour. I have an Helper that returns a date object, takes date and hour and mix it up with carbon... now i have got to check that the begin date is minor than the end date... I wanna do this in the request file... any suggestions ? Thx !
public function rules()
{
$rules = [
'beginDate' => 'required|date',
'beginHour' => 'required',
'endDate' => 'required|date',
'endHour' => 'required',
'user_list' => 'required',
];
$begin = Helper::mergeDateHour($this->beginDate,$this->beginHour);
$end = Helper::mergeDateHour($this->endDate,$this->endHour);
if(!$begin->lt($end)){
return false;
}
return $rules;
}
This is something you can do if you just want to check date.
'endDate' => 'required|date|after:beginDate'
If not, You can try using DateTime.
For example,
$validator = Validator::make(Input::all(), User::$test);
if ($validator->passes()) {
$beginDate = Input::get("beginDate");
$beginHour = Input::get("beginHour"); // assumming H:i
$endDate = Input::get("endDate");
$endHour = Input::get("endHour");
$begin = new DateTime(date("Y-m-d H:i:s", strtotime($beginDate." ".$beginHour.":00")));
$end = new DateTime(date("Y-m-d H:i:s", strtotime($endDate." ".$endHour.":00")));
if($begin > $end)
echo "1 is faster";//return and say end supposed to be faster
else
echo "2 is faster";
} else {
return Redirect::back()->with('message', 'Please fix the following errors:')->withErrors($validator)->withInput();
}
I have a registration form with 3 select fields (month, day, year) which I want to grab, convert to proper date format, and validate. So, below are the 3 select boxes.
<div class="birthday_selects">
<select name="birthday_month">
....
</select>
<select name="birthday_day">
....
</select>
<select name="birthday_year">
....
</select>
</div>
I've read that I can use the following, but I get the error "...Http\Input not found..."
$birthday = Input::get('birthday_month')."-".Input::get('birthday_day')."-".Input::get('birthday_year')'
Okay, I can dd($birthday) and it comes out in the m-d-y as I've concatenated there. Now, I'm trying to validate that date against a prior date (to see if user is >13 years old). I'm using the following, but no luck.
public function postSignup(Request $request)
{
$birthdate = Input::get('birthday-month')."-".Input::get('birthday-day')."-".Input::get('birthday-year');
$this->validate($request, [
$birthdate => 'required',
]);
dd($birthdate);
}
When just having it be required, it doesn't work.
Your help is appreciated. Thanks!
It's not working because you're doing it wrong. What is wrong with it is the rule.
The rule key must be present in the form field's name.
For your answer, let's assume the $birthday will be 'jul-15-1992'. and you're going to put that variable inside the rule as a key. So, that's not valid because the field will never be present in the form field.
public function formPost(Request $request)
{
$rule = [
'birth_year' => 'required|numeric',
'birth_day' => 'required|numeric',
'birth_month' => 'required|numeric', // may be a string
];
$this->validate($request, $rule);
// check if the day is valid for the month manually.
// then form the DOB now.
}
Create Carbon date and add new [birth_day] input:
$all = $request->all();
$year = $all['birthday_year'];
$month = $all['birthday_month'];
$day = $all['birthday_day'];
// Create Carbon date
$date = Carbon::createFromFormat('Y-m-d', $year.'-'.$month.'-'.$day);
//add new [birth_day] input
$request->request->add(['birth_day' => $date->format('Y-m-d')]);
$validatedData = $request->validate([
'first_name' => 'required|string|max:255',
'last_name' => 'required|string|max:255',
'email' => 'required|string|email|max:255',
'password' => 'required|string',
'birth_day' => 'required|date_format:Y-m-d|before:today',// validate birth day
]);
Hope this will help you
I have the following query
public static function createConversation( $toUserId )
{
$now = date('Y-m-d H:i:s');
$currentId = Auth::user()->id;
$results = DB::table('pm_conversations')->insert(
array( 'user_one' => $currentId, 'user_two' => $toUserId, 'ip' => Request::getClientIp(), 'time' => $now )
);
return $results;
}
How would i return the id of the row just inserted?
Cheers,
Instead of doing a raw query, why not create a model...
Call it Conversation, or whatever...
And then you can just do....
$result = Conversation::create(array( 'user_one' => $currentId, 'user_two' => $toUserId, 'ip' => Request::getClientIp(), 'time' => $now ))->id;
Which will return an id...
Or if you're using Laravel 4, you can use the insertGetId method...In Laravel 3 its insert_get_id() I believe
$results = DB::table('pm_conversations')->insertGetId(
array( 'user_one' => $currentId, 'user_two' => $toUserId, 'ip' => Request::getClientIp(), 'time' => $now )
);
This method requires that the id of the table be auto-incrementing, so watch out for that...
The last method, is that you can just return the last inserted mysql object....
Like so...
$result = DB::connection('mysql')->pdo->lastInsertId();
So if you choose that last road...
It'll go...
public static function createConversation( $toUserId )
{
$now = date('Y-m-d H:i:s');
$currentId = Auth::user()->id;
$results = DB::table('pm_conversations')->insert(
array( 'user_one' => $currentId, 'user_two' => $toUserId, 'ip' => Request::getClientIp(), 'time' => $now )
);
$theid= DB::connection('mysql')->pdo->lastInsertId();
return $theid;
}
I would personally choose the first method of creating an actual model. That way you can actually have objects of the item in question.
Then instead of creating a model and just save()....you calll YourModel::create() and that will return the id of the latest model creation
You can use DB::getPdo()->lastInsertId().
Using Eloquent you can do:
$new = Conversation();
$new->currentId = $currentId;
$new->toUserId = $toUserId;
$new->ip = Request::getClientIp();
$new->time = $now;
$new->save();
$the_id = $new->id; //the id of created row
The way I made it work was I ran an insert statement, then I returned the inserted row ID (This is from a self-learning project to for invoicing):
WorkOrder::create(array(
'cust_id' => $c_id,
'date' => Input::get('date'),
'invoice' => Input::get('invoice'),
'qty' => Input::get('qty'),
'description' => Input::get('description'),
'unit_price' => Input::get('unit_price'),
'line_total' => Input::get('line_total'),
'notes' => Input::get('notes'),
'total' => Input::get('total')
));
$w_id = WorkOrder::where('cust_id', '=', $c_id)->pluck('w_order_id');
return $w_id;