Laravel Query Builder - Where date is now using carbon - laravel

How to get only date on database column, I have difficulties using Carbon on controller:
$data['nowUser'] = User::where('date', Carbon::today()->toDateString())->get();
Date column looks like this in the database:

That is a DATETIME column, so there's no need for additional formatting the Carbon instance. However you need to use whereDate if you want the fetch all users for which the date column contains today's date:
$data['nowUser'] = User::whereDate('date', '=', Carbon::today())->get();
Because when you pass Carbon::today() to the Query Builder method, the __toString method will be automatically called and return a DATETIME string with the format from Carbon::DEFAULT_TO_STRING_FORMAT, which is exactly that MySQL format Y-m-d H:i:s.

Related

Laravel 8: why is sorting by date in eloquent is wrong, using Carbon

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]]]

Laravel 5: Query Builder: Get the record using date in datetime datatype

I have column date and the data type is datetime, now I want to fetch all the related date with a certain date.
I want to monitor how many items I've bought in a certain year but what I have right now is, I'm not getting any value.
Example
My date is:
$date['start_date'] = "2019-01-01";
$date['end_date'] = "2019-12-31";
I have 3 records
1)
name: Laptop
date(date bought): 2018-03-05 14:23:00
2)
name: Shoes
date(date bought): 2019-03-05 23:05:00
3)
name: Bag
date(date bought): 2019-10-05 18:35:00
Model
return DB::table('x')
->whereBetween('date', [date('Y-m-d', strtotime($date['start_date'])), date('Y-m-d', strtotime($date['end_date']))])
->get()->toArray();
Question: Is my query wrong?
You can use like as you would in normal SQL and treat the datetime field as you would a text field
return DB::table('x')->where('date', 'like', "2019-%")->get()->toArray();
or even better with your Model
return YourModelX::where('date', 'like', "2019-%")->get()->toArray();
or you use whereBetween with the format of your cells in the database:
// datetime
return YourModelX::whereBetween('date', ['2019-01-01 00:00:00','2019-12-31 23:59:59'])->get();
// date
return YourModelX::whereBetween('date', ['2019-01-01','2019-12-31'])->get();

Set input default date format for dates in a model

There is a way to set the default date format of input dates in a model?
I need to create a model with data received in JSON format and date are formatted as Y-m-dTH:i:sP, but date in the DB are stored in the default Y-m-d H:i:s format. I added all the date fields in the $dates property of the model, but now when i create the model setting all the params in the constructor, like this:
$model = new Model($params);
I get a Carbon conversion error (InvalidArgumentException) because it tries to create a Carbon object from the Y-m-d H:i:s format.
I know Date mutators, but if i set
protected $dateFormat = "Y-m-d\TH:i:sP";
it creates the Carbon object correctly but i get an error while storing in the DB, because it tries to store the record with that format.
Is there a standard way to achieve what I need without converting the date format on each date param?
//date format = Y-m-dTH:i:sP
$date = '2011-09-16T11:38:23-05:00';
$new_date = date_format(date_create($date), 'Y-m-d H:i:s');

Laravel: Check if time + 4 hours has passed

I store in my database a date format like this:
2017-02-22 16:55:40
I added it to my database like this:
Carbon::now();
I need to check if 4 hours passed since this date.
How I can do this? I couldn't figure out how I can convert this format into Carbon or timestamp.
If you are using Laravel and the date is a Carbon instance from a Model you have access to the whole Carbon API.
You can use the Difference API of Carbon for this specific purpose.
echo $model->thedate->diffInHours($now, false);
If your model does not threat the date as a carbon instance you can cast it by adding the date to the dates array of the current model like so
protected $dates = [
'field_name',
];
Check out Date casting for more information
Update with an explicit example
$user = User::first();
// This will return the difference in hours
$user->created_at->diffInHours(Carbon\Carbon::now(), false);
You can convert it to a Carbon object with:
Carbon::parse('2017-02-22 16:55:40');

Convert unix timestamp to normal Date in Json

I am using laravel 5.0. I am getting data from controller as json. I am having value like this.
{"timstamp_date":"1434360957"},
I need to convert this unix timestamp value as Normal Date Like (15-06-2015) or (15-March-2015).
I have used Date(timstamp_date) but it is showing current time only. Not my timstamp date
You could use:
date("d-m-Y H:i:s", 1434360957);
EDIT
You could try;
var dateTime = new Date(1434360957*1000);
var formatted = dateTime.toGMTString();
https://jsfiddle.net/sp57Lnpf/
Use the date function. You need to specify the format as the first parameter:
date("d-m-Y", $timestamp_date)
http://php.net/manual/en/function.date.php
Laravel also comes with Carbon you could use that if you wanted to for further manipulation of the data if you so required it.
http://carbon.nesbot.com/docs/

Resources