Laravel Eloquent Model Custom Function Example

By Hardik Savani April 19, 2021 Category : Laravel

Hi Dev,

Now, let's see example of laravel eloquent model custom function example. if you want to see example of laravel create custom function in model then you are a right place. This tutorial will give you simple example of laravel model custom functions. you can see laravel model call function.

We almost need to create custom functions in our eloquent model. if you are new and you don't know how to create custom function in model then in will let you know simply. you can easily use custom function with laravel 6, laravel 7 and laravel 8 version.

here, we will simply create age() so basically, it will returns age from date of birth. so i created patient model with age() and you will see how to call model function in controller too.

Let's see.

app/Models/Patient.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

use Illuminate\Database\Eloquent\SoftDeletes;

use Carbon\Carbon;

class Patient extends Model

{

use SoftDeletes;

protected $dates = ['deleted_at'];

/**

* The attributes that are mass assignable.

*

* @var array

*/

protected $fillable = ['code', 'first_name', 'last_name', 'address' 'birth_date'];

/**

* Get the user's full name.

*

* @return string

*/

public function getAgeAttribute()

{

return Carbon::parse($this->birth_date)->age;

}

}

Controller Code:

<?php

namespace App\Http\Controllers;

use App\Models\Patient;

class SignaturePadController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function index()

{

$patient = Patient::find(1);

dd($patient->age);

}

}

Output:

25

I hope it can help you...