Working with date, we need to display formatted date to user and store date into the database into specific format. Laravel provides a few ways to implement this functionality like an accessor or by defining a custom function or by converting the date every time. For this example, we will define the accessor function into the eloquent model and convert the date format.
Here, we will use carbon to convert the date object and also perform type casting of that column.
In this example, we will create the formatDate() function into our User model and use it whenever required. The scope of this function is only for a particular model object. For demonstration, we will add a new column to user migration and use it.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
protected $fillable = [
'name',
'email',
'password',
'join_date'
];
protected $hidden = [
'password',
'remember_token',
];
protected $casts = [
'email_verified_at' => 'datetime',
'join_date' => 'date'
];
public function formatDate(){
return $this->join_date->format('d-m-Y');
}
}
In above example, we have created method with formatDate() name which will use joining date of user and returns into formatted date.
Here, we have also added join date into fillable and cast as date. So whenever you use formatDate() function then it will convert date from model object into formatted using Carbon.
Let's take an example to understand how this works.
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Storage;
class TestController extends Controller
{
public function index(){
$user = User::create([
'name' => "Test",
'email' => "test@gmail.com",
'password' => Hash::make('password'),
'join_date' => "2022-08-15"
]);
dd($user->formatDate());
}
}
Here, we have added static data into user model and perform format date on that user data. While storing data we have passed Y-m-d format and then use this function it will return date into d-m-Y format. We can use this function while displaying data to the user and perform queries or logic in another format.
In this example, we have created a method that converts date format for that you can also use an accessor. It's a simple example to demostrate a custom method in Laravel model. You can alter logic as per your requirement.
Ask anything about this examples