Format date time properly with laravel and carbon

- 1 answer

Ad

I try to add date and time into my database but I have problems:

First: I create a form:

<div class="row">
<div class="form-group col-md-6">

    {!! Form::label('roba_spremna','The cargo is ready:') !!}
    {!! Form::text('roba_spremna', null, ['class'=>'form-control']) !!}
</div>
<div class="form-group col-md-6">

    {!! Form::label('auction_end','Auction close at:') !!}
    {!! Form::text('auction_end', null, ['class'=>'form-control']) !!}
</div>
</div>

After that I add bootstrap-datetimepicker (js library):

$( document ).ready(function() {
                $(function () {
                    $('#roba_spremna, #auction_end').datetimepicker();
                });
            });

and at Article model I write:

 protected $fillable = [
        'title',
        'body',
        'roba_spremna',
        'auction_end'
    ];

    protected $dates = [
        'roba_spremna',
        'auction_end'
    ];

    public function setRobaSpremnaAttribute($date){
        $this->attributes['roba_spremna']= Carbon::createFromFormat(''m/d/Y h:i a', $date);
    }

Now When I try to store date with time at my database so when I submit form I get this error:

InvalidArgumentException in Carbon.php line 425: Unexpected data found. Unexpected data found. Unexpected data found. Trailing data

enter image description here How I can solve my problem?

Ad

Answer

Ad

Best way to solves this is to debug your controller or use the dd() function. Anyway your goal is to see what exactly your date looks like while you're in the controller.

Depends if you inject the request as a parameter in the controller function or use the facade dd call should looks like this :

dd($request->get('roba_spremna'));

or via the facade :

dd(\Request::get('roba_spremna'));

Then you need to compare the date format with your mask. Ultimately copy the date you got from dd(), then launch

php artisan tinker

create a variable containing the date as a string and try to create manually a carbon object with it to see what mask you really need.

Ad
source: stackoverflow.com
Ad