How to change the date format in laravel view?

Member

by rollin , in category: PHP Frameworks , 3 months ago

How to change the date format in laravel view?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by hal.littel , 3 months ago

@rollin 

In Laravel, you can change the date format in your view by using the format() function of the Carbon library, which is included by default in Laravel.


Here is an example of how you can change the date format in your view:

  1. First, make sure you have the Carbon library imported at the top of your view file:
1
use CarbonCarbon;


  1. Next, use the Carbon class to format the date. Assuming you have a variable called $date that holds the date value, you can format it like this:
1
{{ Carbon::parse($date)->format('Y-m-d') }}


In the above example, Carbon::parse() converts the $date variable to a Carbon instance, and ->format('Y-m-d') formats it as "Year-Month-Day". You can change the format pattern as per your requirement.

  1. If you want to change the date format for a model attribute in Laravel's blade template, you can use the accessor of the attribute in your model file. For example, if you have a User model with a created_at attribute that holds the date value, you can define an accessor like this:
1
2
3
4
public function getCreatedAtAttribute($value)
{
    return Carbon::parse($value)->format('Y-m-d');
}


Now, when you access the created_at attribute in your view like $user->created_at, it will be automatically formatted according to the accessor.


This is how you can change the date format in Laravel view.