Problem converting date from a bootstrap datepicker to a different format - laravel

Working on an app whereby am capturing some input fields using bootstrap datepicker. Am displaying the format in dd/mm/yy format to the user which works fine. On the backend (build in Laravel PHP), I need to convert it to yy-mm-dd format which is the required format when storing the date field in the API.
In the controller when I dump the data I get 28/01/2019 but when I convert it I get 1970-01-01. What could be the issue?
Markup
<div class="form-line registar love {{ $errors->has('dob') ? ' has-error' : '' }}">
<input type="text" placeholder="Date of Birth *" class="form-input dateTextBox" name="dob" id="dob" value="{{isset($user->dob) ? $user->dob : old('dob') }}" required>
</div>
Javascript Logic (Bootstrap datpicker)
var maxBirthdayDate = new Date();
maxBirthdayDate.setFullYear( maxBirthdayDate.getFullYear() - 18 );
maxBirthdayDate.setMonth(11,31);
$( function() {
$( "#dob" ).datepicker({
changeMonth: true,
changeYear: true,
dateFormat: 'dd/mm/yy',
maxDate: maxBirthdayDate,
yearRange: '1900:'+maxBirthdayDate.getFullYear(),
});
});
Controller Logic
public function validateDate(Request $request){
//dd($request->dob);
//28/02/2019 after dd() above
//Convert
$dobCv = date("Y-d-m", strtotime($request->dob));
dd($dobCv);
//1970-01-01 after dd() above
}

Why don't you use Laravel build in Carbon
$date = Carbon::createFromFormat('d/m/Y', $date);
Then you can do $date->toDateTimeString(); or whatever you want to do with the Carbon date object

You can simply use Carbon :
$dobCv = Carbon::createFromFormat('d/m/Y', $request->dob)->format('Y-m-d');
And don't forget the import :
use Carbon\Carbon;

Encode it in json format and send it to the controller

Changing input type text into date might help you.
eg: <input type="date" .......>

You have the problem because forward slash (/) signifies American M/D/Y formatting in strtotime and in your example 28/02/2019 28 is month. So strtotime returns false. I recommend you to use Carbon library as was said above or change / with - if you want your way:
$dobCv = date("Y-d-m", strtotime(str_replace('/', '-', $request->dob)));

Related

Unexpected data found.\nTrailing data

I got this error:
"Unexpected data found.\nTrailing data"
It says that it comes from this LN on my update function:
$fe_ini = Carbon::createFromFormat('d/m/Y H:i', $request->fecha_inicial);
fecha_inicial comes from my blade:
<div class="col-md-4">
<label>Fecha inicial</label>
<input type="datetime-local" name="fecha_inicial" value="2018-01-31T18:00:00" class="form-control input-lg" ng-model="descuento.fecha_inicial" ng-disabled ="desAll" required>
</div>
My store function says:
$fecha_inicial = Carbon::createFromFormat('d/m/Y H:i', $request->fecha_inicial);
Could you help me to find out what am I doing wrong?
Thank you.
As Lagbox says in their comment, your date formats don't match:
The value on your input, 2018-01-31T18:00:00, is not in the format you're passing to createFromFormat() which is 'd/m/Y H:i'.
I suggest just moving to Carbon::parse():
$fecha_inicial = Carbon::parse($request->fecha_inicial);
I solved it by doing this:
$fecha_inicial = Carbon::createFromFormat('d/m/Y, H:i:s', $request->fecha_inicial)->format('Y-m-d H:i:s');
I checked my Payload and the data came with a comma ',' right after the year like this:
'13/09/2022, 11:38:53'
So what I did was to add a comma too in the format from createFromFormat method. Plus, I added ->format('Y-m-d H:i:s') to convert it.
Thanks.

Laravel 8 multi value select filtering

I'm trying to build Laravel project that will have a multi-select dropdown with list of categories. Selecting category should reload the page and apply filter.
"scopeFilter" in my model is actually doing filtering, but here i just need to find a way to properly form URL. The problem is that this code i have:
<form id="cats-form" action="#" method="GET">
<select multiple class="chosen-select" name="test[]">
#foreach($categories->get() as $cat) //this loop goes through existing categories in the system
#php
//if category is part of URL, pre-select it in the select:
$arr = request()->all();
$selected = '';
if(array_key_exists('test', $arr)) {
$testArr = $arr['test'];
$selected = in_array($cat->id, explode(',', $testArr)) ? 'selected' : '';
}
#endphp
<option {{ $selected }} value="{{ $cat->id }}">{{ $cat->name }}</option>
#endforeach
</select>
</form>
<script>
$(".chosen-select").chosen({ })
$('.chosen-select').on('change', function(evt, params) {
$('#cats-form').submit();
});
</script>
Is actually giving me this URL:
http://localhost:11089/?test%5B%5D=19&test%5B%5D=5
While i actually need this:
http://localhost:11089/?test=19,5
I guess it's a trivial problem to solve for someone with better knowledge of Laravel, can you tell me pls what i'm doing wrong here?
This is rather how the language or framework or library reads an URL query string. Assuming that your prefered way of URL string is a valid format (as I usually see the format ?arr[]=val1&arr[]=val2 and never see the second format that you preferred), both query string formats should be acceptable to PHP.
As Yarin stated that the best way PHP reads an array is the first method, you don't have to worry too much because the decoded URL query string is exactly in the first format.

Extracting day, month, years and hours using laravel blade

I have a small problem in my laravel application. In my blade file, I would like to extract data from timestamp sql query result like using twig filter in Symfony.
Here is what I would like to do (here I used twig filter syntax)
<div class="day">{{ $post->published_at|date("d") }}</div>
<div class="month">{{ $post->published_at|date("m") }}</div>
How to do the samething in Larave blade file ?
Note that I tried to use the syntaxe below but it is not working for me
<div class="day">{{ $post->published_at->format('d') }}</div>
<div class="month">{{ $post->published_at->format('M') }}</div>
My project used laravel 8.
Is there somoene can help me please.
I think you can use Carbon.Here i assume your published_at format in db is timestamp or datetime
Carbon\Carbon::parse($post->published_at)->format('d')
As suggested by Alberto Sinigaglia in comment,If you cast published_at in your model like below then you can easily format without manually parsing.
In your model
protected $casts = [
'published_at'=>'date' // or datetime
];
then in your view
{{$post->published_at->format('d')}}
Use strtotime and date functions:
<?php
$time = strtotime($post->created_at);
$day = date('D', $time);
?>
<div class="day">{{ $day }}</div>

Better Way to use Laravel old and Vue.js

Im working using vue.js 2.0 and Laravel 5.4 I would like to know if exits a better way to send data Controllers -> views without lost the value, overwrite by the v-model
Because after charge vue.js this take the value in data that is define in this way
data: {
ciudad:'',
}
If I try to do something like that
<input class="form-control" id="ciudad" name="ciudad" type="text" v-model="documento.ciudad" value="{{ $documento->ciudad }}" >
I lost the value sending by the controller
Vue really expects you to init data from the view model which then updates the view, however, you want to use data in the view to update the underlying model data.
I think the easiest approach to this is to write a directive that inits the value from the HTML, so you don't need to directly access the DOM:
Vue.directive('init', {
bind: function(el, binding, vnode) {
vnode.context[binding.arg] = binding.value;
}
});
It's a little abstract so it's worth looking at Directive Hook Arguments section of the docs.
This can then be used like:
<input v-model="ciudad" v-init:ciudad="'{{ old('ciudad') }}'">
Here's the JSFiddle: https://jsfiddle.net/v5djagta/
The easy way to do this for me was in this way:
Laravel Controller
$documento = ReduJornada::where("id_documento",$id)->first();
return view('documentos.redujornada')->with(compact('documento'));
Laravel View
<input class="form-control" id="ciudad" v-model="documento.ciudad" value="{{ old('ciudad', isset($documento->ciudad) ? $documento->ciudad : null) }}" >
Vue.js
data: {
ibanIsInvalid : false,
documento: {
ciudad: $('#ciudad').val(),
}
In this way I can use the same view to create and edit an object, using the same form, even use laravel validation without lost the data after refresh.
If you know a better way to do that please tell me... Thanks
You have to define your value first, for example :
$oldValue = $request->old('value');
and then pass it to vue component, define props and use it in v-model
<script>
export default {
props: {
$oldValue : String,
}
};
</script>
<template>
<input class="form-control" id="ciudad" name="ciudad" type="text" v-model="oldValue">
</template>

JQuery datePicker not working for dynamically created input element

I am trying to integrate the jquery datepicker to an input field which i am creating dynamically using script..
my script is like...
function getDate(id)
{
$('.pop-up-link').show();
$.ajax({
url : 'gettartDate.jav',
data : 'Id='+id,
success : function(dateStr)
{
var htmlStr = 'Start Date : <input type="text" class="datepicker" id="startDateId" value="'+dateStr.StartDate+'"/>';
$(".pop-info").html(htmlString);
$('.datepicker').datepicker({ dateFormat: 'yy-mm-dd', changeMonth: true, changeYear: true});
}
}
I am calling this script when i need to edit the date in database and to add new entry to database. When i need to add new entry, im setting id as 0 and returning a blank string..
Now my problem. the datepicker works perfectly for edit functionality.. But when i add a new entry, the datepicker ui comes.. But the date is not updating to that input field. Again, when i put an alert to display selected date,i noticed that only date is changing.. The year and month is not changing, even when i change it
It could be down to the fact you are dynamically adding the datepicker with the same ID's, i was having the same issue with dynamically created datepickers. if there was anyway you could take out the Id attr and use the Name attr it should work.
so you should have the following
var htmlStr = 'Start Date : <input type="text" class="datepicker" name="startDateId" value="'+dateStr.StartDate+'"/>';
Try using the refresh method on .datepicker like so:
$( ".datepicker" ).datepicker( "refresh" );

Resources