Laravel Eloquent Model Custom Function Example
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
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- Laravel Eloquent Sum Multiple Columns Example
- Laravel Eloquent Group By Example
- Delete All Records from Table in Laravel Eloquent
- Laravel Eloquent take() and skip() Query Example
- Laravel Eloquent whereNotBetween() Query Example
- Laravel Eloquent whereBetween() Query Example
- Multiple orWhere Condition in Laravel Eloquent
- Laravel Eloquent Where Query Examples
- Laravel Eloquent Relationships Tutorial From Scratch
- Laravel Many to Many Eloquent Relationship Tutorial
- Laravel Has Many Through Eloquent Relationship Tutorial