I am coding a feature in Laravel where a user can use a select box to choose a certain date. By standard, these dates are saved in y-m-d in my table.
I have succeeded in formatting the date to dd/mm/yyyy by using the Eloquent solution, adding to my Eloquent Model called Dataslot:
protected $dates = ['maand'];
Afterwards I could use the following to format the date.
$d = Dataslot::find(1);
$dformat = $d->maand->format('d-m-Y');
In order to pass the ID of the dataslot and the date to my select box, I have chosen to use the lists method.
$dataslots = Dataslot::lists("maand","id");
This returns me an array. I cannot use the format method on this array as I could on the object in the first example.
How can I have an array of formated dates, with the ID as a key, to send to my view?
Untested (I'm on mobile right now) but this should work;
Carbon::setToStringFormat('d-m-Y');
$dataslots = Dataslot::lists('maand', 'id');
You could change Carbon back after with:
Carbon::resetToStringFormat();
this did the trick:
$dataslots = Dataslot::all();
foreach ($dataslots as $o) {
$flatArray[$o->id] = $o->maand->format('d-m-Y');
}
Would this do it?
$dataslots = Dataslots::all()->map(function($dataslot) {
return [$dataslot->id => $dataslot->maand->format('d-m-Y')];
});
Related
example i am passing this date in $date = 2020-12-28 15:15:53
and
in db approve_date = 2020-12-28 15:15:00
i am trying to get all the record of date only like this 2020-12-28
so i tried
public function getdatedInvoice($date)
{
$invoices = Invoice::where('user_id' , Auth::id())->where('is_approved' , 1)->whereDate('approve_date' , $date)->get();
dd($invoices);
return view('approved_invoices', compact('invoices'));
}
but when i try to use whereDate it gives me nothing how i can get that data according to date?
First of all, by default, Laravel will only process the approve_date column from your database as a string, even if you set it as a date_time column.
To make Laravel process it as a real date instead, you need to add this to the top of your Invoice model:
class Invoice extends Model {
protected $dates = [
'approve_date'
];
}
Now you will be able to make date comparisons without getting weird errors.
To make your date formatted the way you want, you can go about it in 2 ways.
You can either set a default date formats on every date column in your model by adding this also to the model:
protected $dateFormat = 'Y-m-d';
https://laravel.com/docs/5.2/eloquent-mutators#date-mutators
You can also do this at runtime in your view: {{ \Carbon\Carbon::parse($invoice->approve_date)->format('Y-m-d') }}
'approve_date' is not a variable... you are missing the $ sign. It should be something like this:
$invoices = Invoice::where('user_id' ,
Auth::id())->where('is_approved' , 1)->whereDate('$approve_date' ,
$date)->get();
that variable is not being declared in the function;
After all that, you have your date like date/time and you should convert the format using (for example) Carbon https://carbon.nesbot.com/docs/
I'm using laravel 5.5 with MySQL database.
Here is my current code:
private function setValidationRule(Request $request,$actionCode) {
$rules = [];
$rules['odaydate'] = 'required|unique:empofday|date_format:"d-m-Y"';
return $rules;
}
public function postCreate(Request $request) {
//Previous code...
$validator = \Validator::make($request->all(),
$this->setValidationRule($request,$actionCode),
$this->setCustomValidationRuleMsg($request,$actionCode)
);
$validator->setAttributeNames($this->setValidationAttributeNames());
if ($validator->fails()) {
$view = $viewPri->withErrors($validator)->withInput();
} else {
$view = $viewSec;
}
return $view;
}
The posting data from client is DD-MM-YYYY = '15-10-2018'.
Then i want to validate the date uniqueness with the rule :
$rules['odaydate'] = 'required|unique:empofday|date_format:"d-m-Y"';
Yes the validation is true (success) but the laravel generated sql was wrong to get the uniqueness :
select count(*) as aggregate from empofday where odaydate = '15-10-2018'
so the resulting sql would be 0 instead of 1.
But if i try manual sql with the following code :
select count(*) as aggregate from empofday where odaydate = '2018-10-01'
resulting value 1.
So, my question is how to set date format for laravel validating uniqueness on database to use d-m-Y format instead of Y-m-d?
Thanks for the help.
If you are using simple text box for date input, I recommend to change that to some date picker plugin, the plugins do have functionality to have a date format that is displayed different than what is sent back to the database.
After that you can remove the date format validation, because it will be managed by the plugin, and unique will run because the format sent by the plugin can be set to be in MySQL format (YYYY-MM-DD)
For jQuery UI Date picker
http://api.jqueryui.com/datepicker/#option-altFormat
I have an array that return the following date time:
$item['created_at'] => "2015-10-28 19:18:44"
And I need this outuput:
"2016-08-10T13:15:00.000+10:00"
Exist any function to convert this date?
Try this:
$dt = new \DateTime('2015-10-28 19:18:44', new \DateTimeZone('Europe/London'));
dd($dt->format('c')); // string '2015-10-28T19:18:44+00:00' (length=25)
Alternatively take a look at Carbon
You can use Laravel's accessors to get "reformatted" created_at.
public function getCreatedAtAttribute($value)
{
//Since Laravel uses Carbon you can do.
return $value->format('c');
}
This way anytime you do something like $model->created_at it will return modified created_at.
If you want to change datetime format for created_at in your database as well, you can use mutators.
More information you can find on the Laravel's docs page.
I am using Laravel 5.1
Few days ago I used protected $dates = ['license_expire'] in my model to convert the string date to Carbon instances. In HTML the default value in create form for the date was Carbon\Carbon::now()->format('Y-m-d')
In order to show alert in home page i used <p>Licence Expired: <b>{{ $employee->license_expire < Carbon\Carbon::now()?'License has expired':$employee->license_expire->diffForHumans() }}</b></p>
Till then diffForHumans() method works fine.
But in that case the edit form's default value also was today's date no matter what was in database(I am using a partial form). To resolve it I change the default value in HTML was NUll. And add another method in my model to show current date in create form.
public function getLicenseExpireAttribute($date)
{
return Carbon::parse($date)->format('Y-m-d');
}
After that when i go to home page i have an FatalErrorException which says Call to a member function diffForHumans() on string
When I check the date with dd($employee->license_expire) it become STRING again.
Can anybody tell me how can I convert the string to Carbon in this situation?
or
Make my create form's default date as today's date, the edit form's date from database and I can use diffForHumans() to show alert in home page?
You were almost there.
Remove protected $dates = ['license_expire']
and then change your LicenseExpire accessor to:
public function getLicenseExpireAttribute($date)
{
return Carbon::parse($date);
}
This way it will return a Carbon instance no matter what.
So for your form you would just have $employee->license_expire->format('Y-m-d') (or whatever format is required) and diffForHumans() should work on your home page as well.
If you're using Laravel 9+, you can alternatively use the updated syntax for defining Accessors :
use Illuminate\Database\Eloquent\Casts\Attribute;
public function licenseExpire(): Attribute
{
return Attribute::make(
get: fn ($value) => Carbon::parse($value);
);
}
Why not try using the following:
$dateTimeString = $aDateString." ".$aTimeString;
$dueDateTime = Carbon::createFromFormat('Y-m-d H:i:s', $dateTimeString, 'Europe/London');
$filter['dateOfService']='06.2021';
$d1 = Carbon::createFromFormat('m.Y', $filter['dateOfService'], 'Europe/Warsaw')->format('m.Y');
Try this
$date = Carbon::parse(date_format($youttimestring,'d/m/Y H:i:s'));
echo $date;
I have a table called events and I'm storing the start date in the datetime format.
However, I'm using a plugin that the requires the dates are formatted to:
YYYY-MM-DD.
I would, therefore, only like to select part of the datetime but without modifying the underling table structure. Is there a way to format the field data for each record as it is being fetched? The reason I ask is because it seems inefficient to go through each record again (like I am at the moment) and format one field.
$this->load->model('event_model');
$events = $this->event_model->get_all();
foreach ($events as $event) {
$start = date('Y-m-d', strtotime($event->start));
//add event to new event array
}
$output = json_encode($events); // I would like to use the formatted date when using json_encode on $events.
I'm using codeigniter with My Model.
why you dont just stored to your generated model?
for example:
$this->load->model("event_model");
$events = $this->event_model->get_all();
foreach($events as $event){
$event->mydate = date('Y-m-d',strtotime($event->start));
}
now pass your $events to the view and use mydate property.
Simply format your date in your sql code
SELECT *, FORMAT(start,'YYYY-MM-DD') as eventStart
FROM events
Format it in the query itself.