Why not have an accessor? http://laravel.com/docs/5.0/eloquent#accessors-and-mutators
Juggling date formats between HMTL input and Eloquent model
I feel as though there must be a simpler way, but it’s Sunday and my brain’s not working at full capacity.
I have an Eloquent model that has an attribute that’s cast as a date:
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class Event extends Model {
protected $dates = ['start_date'];
}
I also have a form for editing this entity. However, trying to display the date in a HTML5 datetime-local control doesn’t work, as Eloquent returns the date value in the format of Y-m-d H:i:s, and the HTML5 <input> expects values to be in the format Y-m-d\TH:i I’ve found.
So now I’ve got to convert from one format to the other when displaying the value in the form, and then on submission convert it back from that format into the first format, so Eloquent can parse it as a Carbon instance. Gah!
Is there a nice way of doing this format juggling? I don’t want to create an accessor for the start_date attribute, because it’s used in other places (and I’d like a Carbon object there and not dates expressed as strings in arbitrary formats).
My thought was to create a FormModel object that wraps Eloquent models and converts any date properties to the desired format. Then in my form request classes convert back from that format to the format Carbon is expecting. But this seems… verbose. I’m going to have dozens of entities with CRUD forms.
Is there a cleaner way?
@martinbean I use presenters for my eloquent models, so you I need to do pretty much anything, but define appropriate method in the presenter and wrap the model. Something like this:
public function start_date()
{
$date = $this->model->start_date;
return ($date instanceof Carbon)
? $date->format('Y-m-d\TH:i')
: str_replace(' ','T',substr($u->created_at, 0, 16));
}
// and call just like any attribute
$model->start_date;
Please or to participate in this conversation.