Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

change the date format in laravel view page

Tags:

date

php

laravel

People also ask

How do I change a date format to a string in laravel?

Change date format by accessor method in model in Laravel 8Create accessor methods getCreatedAtAttribute() and getUpdatedAtAttribute() for created_at and updated_at column in model. These accessors will automatically be called by Eloquent when we retrieve the value of the created_at and updated_at attributes.


Try this:

date('d-m-Y', strtotime($user->from_date));

It will convert date into d-m-Y or whatever format you have given.

Note: This solution is a general solution that works for php and any of its frameworks. For a Laravel specific method, try the solution provided by Hamelraj.


In Laravel use Carbon its good

{{ \Carbon\Carbon::parse($user->from_date)->format('d/m/Y')}}

In your Model set:

protected $dates = ['name_field'];

after in your view :

{{ $user->from_date->format('d/m/Y') }}

works


You can check Date Mutators: https://laravel.com/docs/5.3/eloquent-mutators#date-mutators

You need set in your User model column from_date in $dates array and then you can change format in $dateFormat

The another option is also put this method to your User model:

public function getFromDateAttribute($value) {
    return \Carbon\Carbon::parse($value)->format('d-m-Y');
}

and then in view if you run {{ $user->from_date }} you will be see format that you want.


Easy to use date in blade template use Carbon that way

{{ \Carbon\Carbon::parse($user->from_date)->format('d/m/Y')}}

There are 3 ways that you can do:

1) Using Laravel Model

$user = \App\User::find(1);

$newDateFormat = $user->created_at->format('d/m/Y');

dd($newDateFormat);

2) Using PHP strtotime

$user = \App\User::find(1);

$newDateFormat2 = date('d/m/Y', strtotime($user->created_at));

dd($newDateFormat2);

3) Using Carbon

$user = \App\User::find(1);

$newDateFormat3 = \Carbon\Carbon::parse($user->created_at)->format('d/m/Y');

dd($newDateFormat3);