Create custom method in laravel model

Working with date, we need to display formatted dates to user and store date into the database in a 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 the above example, we have created a method with formatDate() name which will use the joining date of the user and return to the formatted date.

Here, we have also added the join date into the fillable and cast it as date. So whenever you use formatDate() function then it will convert date from a model object into a 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 performed the format date on that user data. While storing data we have passed Y-m-d format and then use this function which will return the 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.

Conclusion

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 demonstrate a custom method in the Laravel model. You can alter logic as per your requirement.