I'm trying to build a query in Laravel using whereBetween and I have a problem with the dates-range. I'm using Carbon to get the inputs, looking like this:
$dateRange = Carbon::parse($request->get('anniversary'));
I received the following error on submit:
DateTime::__construct(): Failed to parse time string (06/01/2019 - 06/30/2019) at position 11 (-): Unexpected character
Then, I changed the $dateRange in this form:
$dateRange = Carbon::parse(str_replace('-', '', $request->get('anniversary')));
After that, this error occured:
DateTime::__construct(): Failed to parse time string (06/01/2019 06/30/2019) at position 12 (0): Double date specification
The whereBetween clause looks like this:
->whereBetween('anniversary', [$dateRange])
Any ideas on how can I fix this?
You need to explode the retrieved Datepicker to two values. (Start Date and End Date)
$dateArray = explode('-', $request->get('anniversary'));
$startDate = $dateArray[0];
$endDate = $dateArray[1];
Now you can use
->whereBetween('anniversary', $dateArray);
Related
Possible duplicates:
Laravel: How to order date, change the date format and group by the date?
Laravel Carbon format wrong date
I created a line chart using chartjs, the chart and data fetching is working fine. However the order of the dates is wrong. It starts off with Aug 2022 instead of Jan 2022.
When I use the orderBy(), it shows orderBy() doesn't exists error.
When I use createFromFormat() of Carbon, it shows missing data error.
Why? I parsed the date with Carbon and the column type is datetime, shouldn't it be working?
This is my laravel collection:
$data = TrafficViolation::select('id', 'violationDateTime')
->get()
->sortBy('violationDateTime')
->groupBy(function($data) {
return Carbon::parse($data['violationDateTime'])->format('M, Y');
});
The orderBy() is a Query Builder method. Once you call get(), you get a Collection instance.
To order the records in your DB you need to call orderBy() first, and than get():
UPDATE:
I have included the records count, and date format. You still need to order the records by the violationDateTime column
$data = User::selectRaw('COUNT(*) as violation_count, DATE_FORMAT(violationDateTime, \'%M, %Y\') as formatedDate')
->groupBy('formatedDate')
->orderBy('violationDateTime')
->get();
if your get a Syntax error or access violation: 1055 you need to change the stritc mode in mysql to false in /config/database.php change ['connections' => ['mysql' => ['strict' => false]]]
I'm trying to get day of week from a variable that is found by maxid, but I only get this error:
Trying to get property 'dayOfWeek' of non-object
Code:
$dailyLog = DailyLog::with(['todoList','user'])->find(\DB::table('daily_logs')->max('id'));
$weekday = $dailyLog->date->dayOfWeek;
$yesterdaysLog = DailyLog::loadByDate(Carbon::now()->subMonth(1)->next($weekday));
I am trying to get the day of week from the first query and compare it to last months same day of week
This: $dailyLog->date is not a Carbon object most probably, hence the reason why you cannot call dayOfWeek.. make sure that the date returns a Carbon instance.
To do that in your DailyLog model add this :
protected $dates = ['date'];
This will make sure that the date is cast to Carbon. But also make sure that for some reason that field is not null also.
I'm having some trouble with date formats in Laravel.
I have a database migration which has a field that looks like the following:
$table->date('Date');
Then, in the controller, I try to fill this field in with the following content:
2019-04-15
But I get the following error:
invalid datetime format: 1292 Incorrect date value: '"2019-04-15"' for column 'Date' at row 1
Any help on which would be the correct way of declaring the field 'Date' in the database would be apreciated.
Thank you very much in advance.
It's to do with strict date typing in MySQL I believe.
Check these answers for more information.
https://stackoverflow.com/a/47946950/1848660
https://stackoverflow.com/a/48998959/1848660
Try using Carbon to generate dates and timestamps.
This will generate a timestamp for the current date and time.
Carbon\Carbon::now();
Or you can parse your current date and convert it to a Carbon stamp
Carbon\Carbon::parse($date)->toDateTimeString();
Documentation:
https://carbon.nesbot.com/docs/
This works with your case:
$date = "2019-04-15";
$formatted_date = Carbon::createFromTimestamp(strtotime($date))->format('Y-m-d');
You can go ahead and test your insert. I have tested this. You won't face the 1292 Incorrect date ERROR.
DB::table('yourTable')->insert(['date'=> $formatted_date]);
Try with this,
$table->date ? date('Y-m-d', strtotime($table->date)) : '-';
You should convert your date to string and then apply date function on that for different date format.
I am using query builder to fetch some data but for the created_at date I am using Carbon::parse(), but it's giving me error something like this:
DateTime::__construct(): Failed to parse time string
Can someone tell me what's wrong with this?
My query:
Carbon::parse(DB::table('students_attendances')
->join('students_classes', 'students_attendances.class_id', '=', 'students_classes.id')
->select('students_attendances.id', 'students_classes.class_name', 'students_attendances.created_at')
->orderBy('id', 'asc')->get())->toCookieString();
I'm using Laravel. I get the following error when trying to display a date:
A textual month could not be found Trailing data
Format is j M Y, date is 2014-12-13 10:00:00
I don't get where is the error.
Any toughts?
For future reference: Using createFromFormat with the second parameter not being a Carbon object was giving me this same error. Using Carbon::parse:: instead of createFromFormat seemed to fix the issue:
public function setPublishedAtAttribute($date) {
$this->attributes['published_at'] = Carbon::parse($date);
}