I am new to php and laravel and using laravel 5.2 with MariaDB 10.1.xx.
test table has index and date (yyyymmdd) columns.
I would like to convert date format from yyyymmdd to YYYYmm without using raw query in the select clause.
I tried it as following:
$test = DB::table('test')
->select( 'idx',Carbon::parse('date')->format('Ym') );
and got error as below:
DateTime::__construct(): Failed to parse time string (date) at position 0 (n): The timezone could not be found in the database.
Please let me have any idea to solve this issue using carbon not raw query.
In your model (Test
) add the protected field $dates
:
class Test {
//...
protected $dates = ['created_at', 'updated_at', 'date'];
//...
}
This tells Eloquent that the field date
(and the default timestamp-fields) contains a date. $entity->date
will now contain a Carbon
instance for an entity of type Test
. You can use this to format the date ($entity->date->format('Ym');
)
You could even write an Accessor to do this for you:
class Test {
//...
public function getFormattedDateAttribute() {
return $this->attributes['date']->format('Ym');
}
//...
}
echo $entity->formatted_date;
Other option is to use mutators in your model something like
public function getDateAttribute($value){
return Carbon::createFromFormat('Y-m-d', $value)->toDateTimeString();
}
You can change or work with it as you need