In laravel how do I fetch date as date instead of datetime format? - laravel

In my database some fields are set as date, while others are datetime or timestamp formats. However when fetching data, the "date" fields are also shown with the 00:00:00 time string attached at the end. How can I prevent this?

You can use date/datetime casting with an additional format parameter as described in the Eloquent: Mutators documentation.
class User extends Model
{
protected $casts = [
'created_at' => 'datetime:Y-m-d',
];
}
This will apply the given format when serializing the model to an array or json. If you want to use a different format in your blade templates, you can use the format() function on the datetime property you want to change:
{{ $user->created_at->format('Y-m-d') }} or {{ $user->created_at->toDateString() }}
You will have to add the created_at column to the $dates property of your model though:
protected $dates = [
'created_at',
];
This basically adds 'created_at' => 'datetime' to your $casts.

Related

casts property is not working to change date format

I am trying to change date format while fetching data in this way
protected $casts = [
'due_date' => 'date:d-m-Y',
];
Blade
{{$ticket->due_date}}
It is showing is like
2022-03-13
Casts are for json serialization (json_encode($ticket)). To get the format you want in blade, use Carbon's format method.
{{ $ticket->due_date->format('d-m-Y') }}

Laravel model item set carbon item but returns string

I have added a datetime in the database schema:
$table->dateTime('send_at')->nullable();
I have set the attribute to a Carbon instance in the seeder:
$invoice->send_at = Carbon::now();
When I try to get the type of the attribute inside the controller it returns a string:
dd(gettype($data['invoices'][0]->send_at));
What is going on? And how can I be sure that it's a Carbon Object instead of a string?
On your model, you need to define $dates property to create Carbon instance automatically for the column :
protected $dates = ['send_at'];
On Since Laravel 8:
protected $casts = [
'send_at' => 'datetime',
];

Entity saving to database wrong date format codeigniter 4

My entity looks like this:
class Request extends Entity
{
protected $casts = [
'id' => 'integer',
'added_at' => 'datetime',
'deadline' => 'datetime',
'completed' => 'integer'
];
}
When saving, the model generates the date fields in 'Y/m/d' format for the sql query, hovewer my database can not parse this. How can I force it to generate dates in 'Y-m-d' format when calling $myModel->insert($myEntity) ?
Entities has the option of setters. It performs the validation or conversion in your case whenever you perform save an entity. Lets say you want to change the form of deadline in that case you have to set the Setter for your deadline as follow :
public function setDeadline(string $dateString)
{
$this->attributes['deadline'] = $dateString;
return $this;
}
In the following line : $this->attributes['deadline'] = $dateString; You will use some library like Carbon to format the $dateString and then reassign your variable deadline. Reference link :
https://codeigniter4.github.io/userguide/models/entities.html

How does laravel/lumen dateformat 'U' actually works?

I'm not able get the timestamps with dateformat 'U' working in lumen.
In migration:
$table->timestamps();
In Model:
protected $dateFormat = 'U';
protected $dates = [
'created_at',
'updated_at',
'deleted_at'
];
public function getDateFormat()
{
return 'U';
}
Insert row from controller:
$model = new ApiKey;
$model->random= rand();
$model->name = $name;
$model->scope = $scope;
$model->save();
It does insert the row in the database but with 0000-00-00 00:00:00 values for created_at and updated_at columns.
Also, while retrieving a model via toArray or toJson it thrown exception:
I want lumen to autoupdate the timestamps and retrive timestamps as unixtimestamp format i.e. number of seconds from 1st Jan 1970.
Also, $table->timestamps() didn't create deleted_at column. What do I need to do get this column created via laravel.
Is there any other option than $table->timestamp('deleted_at');?
I've found a solution bay changing timestamps columns to int. But I want the things to be done in laravel way.
Unix timestamps are integers, not compatible with SQL datetime/timestamp fields. If you want to use unix timestamps, use integer field types for storage.
The timestamps() method only creates created_at and updated_at, soft deletes are not enabled by default. This method should not be used if you want integer storage.
If you only want to change the output format when serializing data, use casting:
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'created_at' => 'datetime:U',
];
This is likely caused by the fact that Laravel/Lumen created the date/time columns as the type timestamp not int so you're trying to save wrong type of data in the field, causing the 0000-00-00 00:00:00.
This would also cause the carbon issue as you are trying to createFromFormat with the wrong format compared to the content.
You can use $table->integer('deleted_at'); in your migration to create a deleted_at column.
TL;DR:
Manually create your date time columns with $table->integer('updated_at').
<?php
namespace App\Traits;
use Illuminate\Support\Carbon;
trait sqlServerDateFormat
{
public function fromDateTime($value)
{
return Carbon::parse(parent::fromDateTime($value))->format('d-m-Y H:i:s');
}
}

Datetime on blade laravel

How to get month name on blade laravel ?
i tried this but the result is the month number
$training->date_activity->month
as per the documentation of Carbon, your approach is correct.
http://carbon.nesbot.com/docs/#api-getters
Yet it could be the property is not considered a Carbon DateTime.
Can you make sure that in the Training Model you have 'date_activity' as a date mutator?
protected $dates = [
'created_at',
'updated_at',
'date_activity'
];

Resources