ItSolutionStuff.com

Laravel Eloquent Model Custom Function Example

By Hardik Savani • April 16, 2024
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, laravel 8, laravel 9, laravel 10 and laravel 11 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...

Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

📺 Subscribe on YouTube

We Are Recommending You

Laravel Eloquent Sum Multiple Columns Example

Read Now →

Laravel Eloquent Group By Example

Read Now →

Delete All Records from Table in Laravel Eloquent

Read Now →

Laravel Eloquent take() and skip() Query Example

Read Now →

Laravel Eloquent whereNotBetween() Query Example

Read Now →

Laravel Eloquent whereBetween() Query Example

Read Now →

Multiple orWhere Condition in Laravel Eloquent

Read Now →

Laravel Eloquent Where Query Examples

Read Now →

Laravel Eloquent Relationships Tutorial From Scratch

Read Now →

Laravel Many to Many Eloquent Relationship Tutorial

Read Now →

Laravel Has Many Through Eloquent Relationship Tutorial

Read Now →