Create custom method in laravel model

In Laravel, you can create a custom method in Laravel model to handle specific logic like formatting dates or manipulating attributes. This approach keeps your code organized and reusable whenever you access model data.

For instance, we will define a custom method in the model to convert date objects using Carbon and apply type casting, making it easy to display and store dates consistently.

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.

Here we explored adding custom methods in a Laravel model, but when working with collections, you can also get array of IDs from Eloquent collection or model to simplify data handling in your application.