Laravel format datetime - php

I have in my database the date of birth of a user, but I want to format that to something like 27 March 2000. I already have the date of registered and I can format that, but if I try to format the date of birth it gives me the following error:
Call to a member function format() on string
This code I used to show and format the date of birth of a user:
{{ucfirst(Auth::user()->created_at->format("M d Y"))}}
I tried to use this code for the date of birth because it is in a table with all the users:
{{ucfirst($user->birthdate->format("M d Y"))}}
This is the database structure:
http://i.stack.imgur.com/Agchg.png

You need to tell Laravel that your birthdate field is a date, otherwise Laravel will just fetch it as-is and not touch it at all. You do that by adding a protected $dates to the model-class which is an array of all fields which Laravel should treat as dates.
class MyModel extends [...] {
protected $dates = ['bithdate'];
}
This will tell Laravel that birthdate is a date and Laravel will convert it to a instance of Carbon.

Related

Laravel where dates by specific format

In DB Col Name('publish') varchar format d/m/Y for Example 30/1/2020
when try to get dates less than 30/1/2020 get any date less than days
for example
->where('publish','<','30/01/2020')
29/2/2020 less than 30/1/2020 so i get any date under 30 by day not month or year
on your Eloquent model define an accessor to retrive publish as carbon object
public function getPublishAttribute($date)
{
return Carbon::parse($date)->format('d/m/Y');
}
now on your controller compare both date as below
->where('publish','<',Carbon::parse('30/01/2020'))
hope it helps!
You can use DB::raw and str_to_date for the same:
->where(DB::raw('str_to_date(publish, "%d/%m/%Y")'),'<','30/01/2020' )
str_to_date will convert your varchar field to datetime field.
MySQL -> Date and Time Functions-> STR_TO_DATE

Laravel Date Format in Table

I am trying to edit the Migration in laravel so that the birth date gets the format needed. Now I have searched around on forums, and none get to my problem (that or I am stupid)
The format used in the code below does not seem to work, because I get errors on the dd part of the format. I've tried a couple of solutions, including editing the model to re-format the date, but that did nothing.
$table->date(dd, mm, YY)('birth_date');
You should use this in your migration:
$table->date('birth_date');
Dates are always stored in the same format in the database. For example, the MySQL documentation on the DATE datatype says:
The supported range is '1000-01-01' to '9999-12-31'.
It is for your application to change the dates into a format you desire. There are different ways to achieve this. In your views you could use format():
{{ $user->birth_date->format('dd, mm, YY') }}
// or if birth_date can be NULL:
{{ optional($user->birth_date)->format('dd, mm, YY') }}
As an alternative, you could use an Accessor in your model:
public function getBirthDateAttribute($date)
{
if (is_null($date)) {
return null;
} else {
return Carbon::parse($date)->format('dd, mm, YY');
}
}
When you set the dateFormat property, you are defining the format for how dates are stored in the database and how they are formatted when your model is serialized.
When you access your birthdate attribute on the model, you are still going to be given a carbon instance that can be used to format the birthdate in any way you would like.
Note that dateFormat will also change the format for your birth_date attributes.
Also Declare in the model:
class ModelName extends Model
{
protected $casts = [
'birth_date' => 'datetime:d/m/Y', // Change your format
];
}
$table->date('birth_date');
you can save data here format (Y-m-d) like (2019-12-31)
Then when You get this you can show your desire format.
other way,If you think
$table->string('birth_date');
Then save data format (Y-m-d) like (2019-12-31).
When You try to show data your desire format just use Carbon\Carbon & format your date

Date from API call not being accepted in Laravel as a dateTime field

I am getting dates from an API call. The date is formatted in this way
2017-10-19T15:30:00
I want to store this date in my MYSQL database using Laravel Database Migration, currently I am using
$table->dateTime('datetime');
When I store it using a dateTime field as above, all I get is
0000-00-00 00:00:00
When I use a timestamp format, I don't get accurate dates, I just get the current time and date.
How can I solve this? Any help would be appreciated, and please let me know if you want further information.
Luckily, Laravel uses the Carbon class, which makes things a lot easier to modify dates. In your case, you want to do this:
Carbon::createFromFormat('Y-m-d\TH:i:s', $date);
There are two ways you can implement it: you can modify it before you save it to your database, or you can add a mutator on your model.
public function setDatetimeAttribute($value)
{
$this->attributes['datetime'] = Carbon::createFromFormat('Y-m-d\TH:i:s', $value);
}
You may want to build in some validation to see which format the date/time is in before you try to convert it.
in the model you should put:
protected $dates = ['datetime'];
Use Carbon
$dt = Carbon::parse('1975-05-21 22:23:00.123456');
to save:
$model = new Model;
$model->date = $dt; // you can use the carbon object directly
$model->save();

Laravel4 - handling date format between whole application and mysql

In laravel 4 i have lots of database fields that having date type and datetime . but i am need to show date format like dd/mm/yy H:i:s like any format and also have to handle date formation on insertion and update. Is they any way to get works in one place?
Yes you can do that, by creating mutator method in your model; for example, if you have a Post model and has a date_of_birth property and you want to set the date in yyyy/mm/dd H:i:s but user is probably providing the date in a different format. In this case crate a mutator method in the Post model like this:
public function setDateOfBirthAttribute($value)
{
// value will be the given date by user
$dt = \Carbon\Carbon::createFromFormat('Y/m/d H:i:s',$value)->toDateString();
$this->attributes['date_of_birth'] = $dt;
}
To access the date just create an accssor method like:
public function getDateOfBirthAttribute()
{
return \Carbon\Carbon::createFromFormat('d-m-Y H:i:s', $this->date_of_birth);
}
Now the date_of_birth will be inserted using the format that you have used in the mutator method and when you'll show that date, it'll be displayed using the format that you have used in the accessor method. You may also check the Date Mutators.
A must have package for dates is Carbon. Take a look at the documentation on GitHub: https://github.com/briannesbitt/Carbon

How can I select all Eloquent models from a MySQL database inserted today, within the last week or the last month?

I have an Eloquent Model (Test) associated with a MySQL table called tests, with the following structure:
tests
id int
created_at date
updated_at date
correct boolean
I am trying to select only those tests created today, within the last 7 days and within the last month, something like this (pseudocode):
$todays_tests = Test::where('created_at','=', 'today');
$this_weeks_tests = Test::where('created_at','=', 'last 7 days');
$this_months_tests = Test::where('created_at','=', 'last month');
I'm sure Laravel provides an easy way to do this but I'm not sure how best to go about it. Presumably I need to use a raw MySQL query?
Many thanks,
I am sure you can do some nice things with the Carbon plugin. The Carbon documentation: https://github.com/briannesbitt/Carbon
For example for created today, if you add this in your Test model:
public function scopeCreatedToday($query)
{
return $query->whereBetween('created_at', array(Carbon::today(), Carbon::today()->addDay()));
}
You will be able to do: $tests = Test::createdToday()->get();.

Categories