Create custom method in laravel model

Working with dates, we need to display formatted dates to users and store dates in the database in a specific format. Laravel provides a few ways to implement this functionality like an accessor 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 a date. So whenever you use the formatDate() function then it will convert the 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 the user model and performed the format date on that user data. While storing data we have passed the Y-m-d format and then used 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.