In Laravel, working with dates is a common requirement, especially when displaying data to users. By default, dates are stored in a standard format in the database, but you may want to display them in a different format. In this tutorial, we will explore how to change the date format in a Laravel view page.
Laravel provides several ways to work with dates, including using the Carbon library, which is included by default. We will start by looking at how to use Carbon to format dates.
Using Carbon
Carbon is a powerful library that makes working with dates in PHP much easier. To use Carbon to format a date, you can parse the date string and then call the format
method to specify the desired format.
{{ \Carbon\Carbon::parse($user->from_date)->format('d/m/Y') }}
In this example, we are parsing the $user->from_date
attribute and formatting it as a string in the ‘d/m/Y’ format.
Using Date Mutators
Another way to format dates is by using date mutators. Date mutators allow you to specify which columns on your model should be treated as dates. To use date mutators, you need to add the column name to the $dates
array on your model.
protected $dates = ['from_date'];
Once you have added the column to the $dates
array, you can access it as a Carbon instance and call the format
method to specify the desired format.
{{ $user->from_date->format('d/m/Y') }}
Using Accessors
Accessors are another way to format dates. An accessor is a method on your model that allows you to modify the value of an attribute before it is accessed. To create an accessor for the from_date
attribute, you can add a method to your model.
public function getFromDateAttribute($value)
{
return \Carbon\Carbon::parse($value)->format('d-m-Y');
}
In this example, we are creating an accessor for the from_date
attribute that formats it as a string in the ‘d-m-Y’ format. To access the formatted date, you can simply call the from_date
attribute on your model.
{{ $user->from_date }}
Using PHP’s strtotime Function
Finally, you can also use PHP’s strtotime
function to format dates. This method is not as elegant as using Carbon or date mutators, but it works.
date('d/m/Y', strtotime($user->from_date));
In this example, we are passing the $user->from_date
attribute to the strtotime
function and then formatting it as a string in the ‘d/m/Y’ format using the date
function.
Conclusion
Formatting dates in Laravel is easy thanks to the Carbon library and date mutators. By using one of these methods, you can display dates to your users in a format that makes sense for your application.