This post was last updated on July 7th, 2021 at 08:17 am
In this article, we will show you Laravel Eloquent Model Custom Function Demo. This article will give you simple example of Laravel Eloquent Model Custom Function Demo. you will learn Laravel Eloquent Model Custom Function Demo.
This article will give you simple example of Laravel Eloquent Model Custom Function Demo of how to add Eloquent Model Custom Function in laravel 6, laravel 7 and laravel 8 version.
here, we will simply create age() so, 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 to.
Step 1 :- 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; } }
Step 2 :- 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