Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

shenka's avatar

Form model binding & Date & Carbon

Hi,

I can define an "Accessor" to format a date field (Carbon) coming from the database, and then, thanks to "Form Model Binding" that field shows up perfectly formatted in the form.

This is great, but, what if i need to play with that date with Carbon, for example, add one day. I mean, How can I have the best of both worlds, the Carbon object and the accessor for formatting the date on the Form model binding.

Thanks in Advance.

0 likes
10 replies
rodrigo.pedra's avatar

It is not quite clear to me what exactly you want to do... Let me give a shot

  1. If your date is stored as one of the SQL date types (datetime, date, etc.) and you want Eloquent to automatically convert them to a Carbon instance, just override Eloquent's getDates() method:
public function getDates()
{
    return ['created_at', 'updated_at', 'custom_date'];
}

There is no need to write an acessor for that.

  1. The form part is what I did not understand, do you want to manipulate the Carbon instance prior to populating the form?

If so, and if you are using plain HTML, I think this will do it:

<input type="date" name="custom_date" value="{{ old('custom_date', $model->custom_date->addDay()->format('Y-m-d')) }}">

As you mentioned you are using Form model binding, I think the easiest way is to update your custom date attribute before sending the model to the view.

shenka's avatar

Thank you Rodrigo,

This is exactly how i got it implemented at the moment, but, I was hoping, since I'm using Form model binding, {{ Form::model($user) }}, to have :

{{ Form::text('custom_date', null, array('class' => 'form-control') ) }} <--- Just like any other field on the form

and not :

{{ Form::text('custom_date', $user->custom_date->format('d/m/Y'), array('class' => 'form-control') ) }}

It's possible? and still have the Carbon object...

rodrigo.pedra's avatar

See if this what you want:

[ http://laravel.com/docs/5.0/eloquent#timestamps]

Providing A Custom Timestamp Format

If you wish to customize the format of your timestamps, you may override the getDateFormat method in your model:

class User extends Model {
    protected function getDateFormat()
    {
        return 'd/m/Y'; // changed to match your format
    }
}
shenka's avatar

I'm afraid it's not working because my date field is a "date" field like "2015-03-12".

Thanks again

shenka's avatar

Let me explain myself with code:

The Model:

class MyModel extends Eloquent {

    protected $dates = array('mydate');

    public function setMydateAttribute($date)
    {
        $this->attributes['mydate'] = Carbon::createFromFormat('d/m/Y', $date);
    }
}

The View:

{{ Form::model($mymodel) }}

{{ Form::text('mydate', $mymodel->mydate->format('d/m/Y'), array('class' => 'form-control') ) }}

{{ Form::close() }}

With this implementation I'm able to play with the Carbon instance of 'mydate' and the date is displayed correctly in the view, except when mydate is null.

Any thoughts?

Thanks again

rodrigo.pedra's avatar

For the null problem you can use a accessor [ http://laravel.com/docs/5.0/eloquent#accessors-and-mutators ]

class MyModel extends Eloquent {

    protected $dates = array('mydate');

    public function setMydateAttribute($date)
    {
        $this->attributes['mydate'] = Carbon::createFromFormat('d/m/Y', $date);
    }

    public function getMydateAttribute($date)
    {
    if (is_null($date))
        {
            return Carbon::now(); // instance of carbon with current timestamp
        }
        
        return $date;
    }
}
shenka's avatar

Thank you Rodrigo,

That's the problem, If I use an accessor then I can't use the Carbon object again. In addition, I want to return an empty string in case of null.

I'll need to use a presenter for this?

Thanks again.

rodrigo.pedra's avatar
Level 56

For returning a Carbon instance the accessor can be slightly modified:

    public function getMydateAttribute($date)
    {
        if (is_null($date))
        {
            return Carbon::now(); // if you are going to return null here, do not use the accessor at all
        }
        
        return $this->asDateTime( $date );
    }

But the problem is that you want to show an empty string if you date is null in the database.

Returning a null value or an empty string from the accessor will led to same "trying to get a property of a non-object" error.

For you case, I would do one of the following:

  1. Use an @if...@else right in the blade view. (I'd use this approach if it is a one-time need in the project and I have a tight deadline)
  2. Create a custom form macro. (I'd use this if I'd need it in many places in the project) Take a look here: [ http://laravel.com/docs/4.2/html#custom-macros ] and here: [ http://laravel-recipes.com/recipes/173/creating-form-macros ].
  3. Create a presenter or helper function to format the date value regarding the null/empty string issue. ( Actually I usually go this way, I have a custom Facade just to help with parsing/formatting custom values, specially numbers (we use comma for decimal separator in Brazil) )
shenka's avatar

Thank you Rodrigo,

I guess I'll go with the helper path. I think the presenter way is so much code for such and easy task.

Thanks again!

Please or to participate in this conversation.