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

fluentd's avatar

Converting datetime picker data to be inserted into mySQL

So I am very new to PHP and Laravel. I believe I have the basics of making a CRUD application but now I am wanting to learn some more. I ran into an issue with taking a date from my Bootstrap theme and converting it to the proper format for SQL. It currently takes YYYY-MM-DD

Here is a sample HTML code

<div class="row">

        <!-- DateRange From Input --> 
        <div class="col-md-6">
          <div class="admin-form theme-primary">
              <label for="datepicker-from" class="field prepend-icon">
                  <input type="text" id="datepicker-from" name="datepicker-from" class="gui-input" placeholder="Datepicker From">
                  <label class="field-icon"><i class="fa fa-calendar-o"></i></label>
              </label>
          </div>
        </div>

        <!-- DateRange To Input --> 
        <div class="col-md-6">
          <div class="admin-form theme-primary">
              <label for="datepicker-to" class="field prepend-icon">
                  <input type="text" id="datepicker-to" name="datepicker-to" class="gui-input" placeholder="Datepicker To">
                  <label class="field-icon"><i class="fa fa-calendar-o"></i></label>
              </label>
          </div>
        </div>
        
      </div>

Here is the sample Javascript

// Datepicker Range From
$("#datepicker-from").datepicker({
  defaultDate: "+1w",
  numberOfMonths: 3,
  prevText: '<i class="fa fa-chevron-left"></i>',
  nextText: '<i class="fa fa-chevron-right"></i>',
  beforeShow: function(input, inst) {
    var themeClass = $(this).parents('.admin-form').attr('class');
    var smartpikr = inst.dpDiv.parent();
    if (!smartpikr.hasClass(themeClass)) {
        inst.dpDiv.wrap('<div class="' + themeClass + '"></div>');
    }
  },
  onClose: function( selectedDate ) {
    $("#datepicker-to").datepicker( "option", "minDate", selectedDate );
  }
});

// Datepicker Range To
$("#datepicker-to").datepicker({
  defaultDate: "+1w",
  numberOfMonths: 3,
  prevText: '<i class="fa fa-chevron-left"></i>',
  nextText: '<i class="fa fa-chevron-right"></i>',
  beforeShow: function(input, inst) {
    var themeClass = $(this).parents('.admin-form').attr('class');
    var smartpikr = inst.dpDiv.parent();
    if (!smartpikr.hasClass(themeClass)) {
        inst.dpDiv.wrap('<div class="' + themeClass + '"></div>');
    }
  },
  onClose: function( selectedDate ) {
    $("#datepicker-from").datepicker( "option", "maxDate", selectedDate );
  }
});
0 likes
31 replies
mstnorris's avatar

You can use Carbon to format the dates correctly.

Carbon::createFromFormat('Y-m-d', $input_name); // whatever your input name is

You'd need to put that in your Controller or wherever you handle the form request.

fluentd's avatar

Ok so where and how exactly would I do that? I know I would need to add

use Carbon\Carbon; 

at the top of the controller. If in the controller is where I would do the conversion. Or would it be in the view that I would do that?

mstnorris's avatar

Yes you do it in your controller.

In your store() method, when you get the data, you can manipulate it there.

Can you paste your controller then I can edit it to show you where.

fluentd's avatar

Just tried this in my store method

public function store(SessionRequest $request)
{

    $request->start = date('Y-m-d', strtotime($request->start));
    dd($request);

    $session = Session::create($request->all());

    return redirect()->route('sessions.index');
}

Also note that the HTML datepicker info that I posted earlier is for two fields the start and end. I made the necessary changes and when I dd($request); I get my start and end data but the

$request->start = date('Y-m-d', strtotime($request->start));

Did not seem to convert anything.

mstnorris's avatar

Can you dd($request) so I can see what inputs you are working with

mstnorris's avatar
$request->start = date('Y-m-d', strtotime($request->start));

Didn't do anything because that isn't what I wrote, you need to do something like:

Carbon::createFromFormat('Y-m-d', $input_name)
fluentd's avatar

Carbon::createFromFormat('Y-m-d', $start); dd($request);

Tried using both $start and $request as the input_name.

$start gives me undefined variable and $request gives me

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

How can I copy the entire dd to show you?

mstnorris's avatar

In your Store method, please can try the following so I can see what request data you are sending.

public function store(SessionRequest $request)
{
    dd($request);
}
mstnorris's avatar

In your Store method, please can try the following so I can see what request data you are sending.

public function store(SessionRequest $request)
{
    dd($request);
}
fluentd's avatar
SessionRequest {#334 ▼
#container: Application {#2 ▶}
#redirector: Redirector {#341 ▶}
#redirect: null
#redirectRoute: null
#redirectAction: null
#errorBag: "default"
 #dontFlash: array:2 [▶]
 #json: null
#sessionStore: null
 #userResolver: Closure {#301 ▶}
#routeResolver: Closure {#313 ▶}
+attributes: ParameterBag {#336 ▶}
+request: ParameterBag {#333 ▼
    #parameters: array:5 [▼
     "_token" => "X9DicFVC93ufZsfqwUmANnPDiVrQ7o9NBxVvLlAo"
    "name" => "Name"
     "description" => "Description"
     "start" => "05/21/2015"
    "end" => "06/20/2015"
 ]
}
+query: ParameterBag {#335 ▶}
+server: ServerBag {#339 ▶}
+files: FileBag {#338 ▶}
+cookies: ParameterBag {#337 ▶}
+headers: HeaderBag {#340 ▶}
#content:   "_token=X9DicFVC93ufZsfqwUmANnPDiVrQ7o9NBxVvLlAo&name=Name&description=Description&start=05%2F21%2F2015&end=06%2F20%2F2015"
#languages: null
#charsets: null
#encodings: null
#acceptableContentTypes: null
#pathInfo: null
#requestUri: null
#baseUrl: null
#basePath: null
#method: "POST"
#format: null
#session: Store {#273 ▶}
#locale: null
#defaultLocale: "en"
}

I also expanded the Request so you can see

mstnorris's avatar

So, if your columns are timestamps then you'd need to do:

Carbon::createFromFormat('m/d/Y', $request->start)->format('Y-m-d');
Carbon::createFromFormat('m/d/Y', $request->end)->format('Y-m-d');

Or, if they don't need the time, then you could change them to the date data type.

fluentd's avatar

In my migration they are setup as follows

$table->date('start');
$table->date('end');

Should I use something else?

mstnorris's avatar

No, see my code above, that should have done it for you.

fluentd's avatar

Getting closer... Looks like a syntax problem?

Also at the top of the controller i added

use Carbon\Carbon;

FatalErrorException in SessionsController.php line 50: Call to undefined method Carbon\Carbon::toFormat()

mstnorris's avatar
Level 55

Oops, it's just format() so remove the to...

mstnorris's avatar

You can check the docs here, they're pretty extensive. There is so much you can do with it. It's a great little package.

fluentd's avatar

Thanks so much for your patients. I will check the docs as well as I have some other things I would like to do with it.

fluentd's avatar

So I made the change to the syntax and it doesnt seem to be working.

Carbon::createFromFormat('m/d/Y', $request->start)->Format('Y-m-d');
Carbon::createFromFormat('m/d/Y', $request->end)->Format('Y-m-d');
dd($request);

+request: ParameterBag {#333 ▼
#parameters: array:5 [▼
  "_token" => "lDWqaK2aFDaaWgSsdeSv4RF9BZnxDm09DFgB6Pjp"
  "name" => "Nick"
  "description" => "Nack"
  "start" => "05/14/2015"
  "end" => "07/16/2015"
]

}

mstnorris's avatar

User lowercase F in format()

Carbon::createFromFormat('m/d/Y', $request->start)->format('Y-m-d');
Carbon::createFromFormat('m/d/Y', $request->end)->format('Y-m-d');
mstnorris's avatar

You need to assign them to a variable, so:

$data = $request->all();
$data['start'] = Carbon::createFromFormat('m/d/Y', $request->start)->format('Y-m-d');
$data['end'] = Carbon::createFromFormat('m/d/Y', $request->end)->format('Y-m-d');
Model::create($data);

Does that make sense?


Nb I haven't mentioned validation at all, as you haven't asked about it, however bear in mind that you must take it into consideration. Make sure you have set the appropriate $fillable fields on your model etc.

1 like
fluentd's avatar

Ya that totally makes sense what you did.

First you take all the fields and assign it to $data

Then you take the $data variable and grab the two fields in which you need to format

Then you save it using create.

That sound right?

fluentd's avatar

Looking over my old code I had the following

$session = Session::create($request->all());

return redirect()->route('sessions.index');

Which it looks like I had no reason to make a variable because the variable isnt being used for anything. My new code is as follows

$data = $request->all();
$data['start'] = Carbon::createFromFormat('m/d/Y', $request->start)->format('Y-m-d');
$data['end'] = Carbon::createFromFormat('m/d/Y', $request->end)->format('Y-m-d');

Session::create($data);
fluentd's avatar

Now i have to do the same thing for Edit and a few other models as well.

fluentd's avatar

For my update method I tried the following:

$data = $request->all();
$data['start'] = Carbon::createFromFormat('m/d/Y', $request->start)->format('Y-m-d');
$data['end'] = Carbon::createFromFormat('m/d/Y', $request->end)->format('Y-m-d');

// $session = Session::findOrFail($id);
// $session->update($request->all());

Session::update($data);

The commented out lines are what I use to have before you showed me how to change the format. This doesnt seem to be doing anything once I click the edit button.

Next

Please or to participate in this conversation.