How to format timestamp data to date format in laravel - laravel

Hello I have laravel project that store data created_at as a timestamp, I would call it from database, but it still show timestamp format, how can I convert it to date format without changing my column type? image
here is my model:
public function getCreatedAtAttribute($value)
{
return Carbon::parse($value)->timestamp;
}
//fungsi untuk merubah format tanggal diubah ke timestamp
public function getUpdatedAtAttribute($value)
{
return Carbon::parse($value)->timestamp;
}
and how should I call it in view or .blade file??
Thank you

To convert to human readable string try changing your functions as below:
public function getCreatedAtAttribute($value)
{
return Carbon::parse($value)->toFormattedDateString();
}
//fungsi untuk merubah format tanggal diubah ke timestamp
public function getUpdatedAtAttribute($value)
{
return Carbon::parse($value)->toFormattedDateString();
}
toFormattedDateString() function will convert to format like Jun 22, 2020. See this article for more alternatives https://www.leonelngande.com/format-dates-for-humans-with-carbon-in-php/.
To use in blade file simply access the parameter like:
$modelvariablename->created_at

In your model:
public function getCreatedAtAttribute(): Carbon {
return Carbon::parse($this->created_at);
}
public function getUpdatedAtAttribute(): Carbon {
return Carbon::parse($this->created_at);
}
For use:
$model->created_at->format('d.m.Y');

If you pass the data from controller to blade You can call in your blade file like this ...
<sapn>{{ $variable->updated_at->toDateString() }}</span>
Or
<span>{{ $variable->updated_at->format('Y-m-d') }}</span>
if you want to convert to inside controller.
public function getCreatedAtAttribute($value)
{
return $value->toDateString();
}
fungsi untuk merubah format tanggal diubah ke timestamp
public function getUpdatedAtAttribute($value)
{
return $value->toDateString();
}
Or you can try carbon
use Carbon\Carbon;
public function getCreatedAtAttribute($value)
{
return Carbon::parse($value)->format('Y-m-d');
}
fungsi untuk merubah format tanggal diubah ke timestamp
public function getUpdatedAtAttribute($value)
{
return Carbon::parse($value)->format('Y-m-d');
}

I would suggest to use eloquent's attribute casting instead.
So for example, make created_at shown as date in d-m-Y format:
protected $casts = [
'created_at' => 'datetime:d-m-Y'
];
Note that attribute casting will only effects the attibute when the model is serialized to json or array (as stated in the doc).

Related

Laravel Mutators and Accessors

I have created mutator date function in model to convert the created_at date into human readable time using diffForHumans().
I have done the following
public function setDateAttribute($value){
return \Carbon\Carbon::parse($value)->diffForHumans();
}
It works fine but it affects in all. it is possible to apply this mutator only on the specified function of the controller rather than all function
A small logic in the mutator would do the job:-
public function setDateAttribute($value){
if ( request()->path() === "/yourURL/To/IndexMethod"){
return $this->attributes['date'] = \Carbon\Carbon::parse($value)->diffForHumans();
} else {
return $this->attributes['date'] = $value;
}
}
the idea is to check by the url.
getting request path helper
EDIT
Comparison using route name is better, as exact path can contain id/slugs.
public function setDateAttribute($value){
if ( \Route::currentRouteName() === "/yourRouteName/To/IndexMethod"){
return $this->attributes['date'] = \Carbon\Carbon::parse($value)->diffForHumans();
} else {
return $this->attributes['date'] = $value;
}
}
getting route name

Laravel set a common validator for all date fields in the system

I have different date fields in different models, I need to validate these date fields format on save of each model accordingly. is this possible?
Of course, you can. You just need to add this code below to your Model.
public static $rules = [
'date'=> 'reqired|date_format:MM:dd:YYYY' //if date is not required, ommite it
]
You can use different formats for your date in your different Models like MM:dd etc. Hope this helps you.
EDIT
To be able to use multiple date formats in a single validator You can define the multi-format date validation in your AppServiceProvider with the following code:
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
Validator::extend('date_multi_format', function($attribute, $value, $formats) {
// iterate through all formats
foreach($formats as $format) {
// parse date with current format
$parsed = date_parse_from_format($format, $value);
// if value matches given format return true=validation succeeded
if ($parsed['error_count'] === 0 && $parsed['warning_count'] === 0) {
return true;
}
}
// value did not match any of the provided formats, so return false=validation failed
return false;
});
}
}
You can later use this new validation rule like that:
'date' => 'date_multi_format:"Y-m-d H:i:s.u","Y-m-d"' //or any other format
Hope this helps, thanks.

Laravel Mutators, Accessors

I've tried to implement mutators into my laravel 5.5. project since it looks like this would be the best way to auto-convert date object but for some reason it's not working. What i try to accomplish is to load a date object from mysql format Y-m-d and convert it to d.m.Y and write date objects with a format of d.m.Y to mysql with the format of Y-m-d. I get constantly errors like "delimiter not found" or "format error" etc.
protected $dateFormat = 'Y-m-d h:i';
protected $dates = [
'joined',
];
function getJoinedAttribute()
{
return $this->attributes['joined']->format('d.m.Y');
}
function setJoinedAttribute()
{
return $this->attributes['joined']->format('Y-m-d');
}
You sould use Carbon library to convert date.
Like this :
public function getDobAttribute($value)
{
return Carbon::parse($value)->format('d/m/Y');
}
public function setDobAttribute($value)
{
$this->attributes['dob'] = Carbon::createFromFormat('d/m/Y', $value)->toDateString();
}

how to Automatically calculate expiry date in backpack laravel?

i have a field which name is month what i want is when user set the month it automatic calculate with created at month and then upload it to database.
PS - sorry i am new at laravel
Please see Edit:
my store method looks like
<?php
namespace App\Http\Controllers\Admin;
use Backpack\CRUD\app\Http\Controllers\CrudController;
// VALIDATION: change the requests to match your own file names if you need
form validation
use App\Http\Requests\ClientsRequest as StoreRequest;
use App\Http\Requests\ClientsRequest as UpdateRequest;
use Carbon\Carbon;
class ClientsCrudController extends CrudController
{
public function setup()
{
$this->crud->setModel('App\Models\Clients');
$this->crud->setRoute(config('backpack.base.route_prefix') . '/clients');
$this->crud->setEntityNameStrings('clients', 'clients');
$this->crud->setFromDb();
}
public function store(StoreRequest $request)
{
// your additional operations before save here
$start_day = Carbon::parse($request->created_at);
$expiry_day = $start_day->addMonths($request->month);
$request->input($expiry_day);
$redirect_location = parent::storeCrud($request);
// your additional operations after save here
// use $this->data['entry'] or $this->crud->entry
return $redirect_location;
}
public function update(UpdateRequest $request)
{
// your additional operations before save here
$redirect_location = parent::updateCrud($request);
// your additional operations after save here
// use $this->data['entry'] or $this->crud->entry
return $redirect_location;
}
}
Assuming that you mean months ammount ( i.e for a monthly payment )
You can do it like this in your store method i.e:
$start_day = Carbon::parse($request->created_at); //get a carbon instance with created_at as date
$expiry_day = $start_day->addMonths($request->user_selected_months); //add X months to created_at date
public function store(StoreRequest $request) {
date_default_timezone_set('asia/calcutta');
$month = $request->month;
$expiry_date = Carbon::now()->addMonths($month);
$request['expiry_date'] = $expiry_date;
}

LARAVEL 5 How to store empty DateTime input to Null value instead of 0000:00:00 00:00 value

i had two input Datetime field.
User can choose to fill in either these two field.
For the empty input Datetime field, i want it to store as Null value in Database.
But currently the empty input Datetime field is store as 0000:00:00 00:00 value in Database. What code should i modified?
you can use model observers to unset the attribute before saving when it is empty. But be sure that the fields are nullable
class Flight extends Model
{
public static function boot()
{
parent::boot();
self::saving(function ($flight_model) {
if(empty($flight_model->arriveDateTime)) unset($your_model->attributes['your_date_field1'];
if(empty($flight_model->departDateTime)) unset($your_model->attributes['your_date_field2'];
});
}
}
this discussion would be a good reference
Update
to do the limitation in the controller you'll use required_without_all:foo,bar,... which as described in doc.s
The field under validation must be present and not empty only when all of the other specified fields are not present
to use it we'll add new rules like
$rules = array(
'arriveDateTime' => 'required_without_all:departDateTime',
'departDateTime' => 'required_without_all:arriveDateTime',
);
$validator = Validator::make(Input::all(), $rules);
and if you're using rules already just append this two roles to them. that's for the controller validation part.
for the view part I'll assume you've two inputs with id="arriveDateTime" and id="departDateTime" the code would be like
$(function() {
<!-- if the first input value changed disable the second input -->
$('#arriveDateTime').on('change', function() {
if ($(this).val() == '') {
$('#departDateTime').prop("disabled", false);
} else {
$('#departDateTime').prop("disabled", true);
}
});
<!-- if the second input value changed disable the first input -->
$('#departDateTime').on('change', function() {
if ($(this).val() == '') {
$('#arriveDateTime').prop("disabled", false);
} else {
$('#arriveDateTime').prop("disabled", true);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input type="text" id="arriveDateTime" />
<input type="text" id="departDateTime" />
All you need is Eloquent Mutators.
Below a simplified example, basically from https://laravel.com/docs/5.4/eloquent-mutators#defining-a-mutator
class User extends Model
{
/* Set or mutate value of property */
public function setDateInputAttribute($value)
{
$this->attributes['date_input'] = $this->dateTimeOrNull($value);
}
/* This method should get another place, because it's not the core of this model */
private function dateTimeOrNull($value)
{
/*
Check if given datetime is valid. Yes? Return original $value
For simplicity, I use PHP's DateTime class
*/
if (DateTime::createFromFormat('Y-m-d H:i:s', $value) !== false) {
return $value;
}
/* Datetime is not valid. Return null */
return null;
}
}
Further
I suppose your datetime format is like yyyy-mm-dd hh:ii:ss
You can uses laravel mutators. Here's one for date of birth.
public function setDob($value)
{
$this->attributes['dob'] = strlen($value)? Carbon::createFromFormat('d/m/Y', $value) : null;
}

Resources