Site Admin
Site Admin Founder of MeaningArticles
1859 Views

Laravel Custom Function In Model

Hello Dev.

Nowaday i can explained to the a way to use Laravel custom Function In Model to your laraval project. Laravel custom function In model is so easy to apply. so you can just comply with my step by step and learn Laravel custom function In model.

in case you want to see instance of laravel create custom feature in model then you are a proper place. you could see laravel model call characteristic.

We almost need to create custom functions in our model. in case you are new and you don't know a way to create custom function in model then it will assist you to recognise easy. you may easily use custom function with laravel 6, laravel 7 and laravel 8 version.

So let's start instance and follow my all step.

Solution

public function getAgeAttribute()
{
    return Carbon::parse($this->birth_date)->age;
}


Step 1: Create Route

Last step to create a route in web.php file and use this code.

routes/web.php

Route::get('function', [UserController::class, 'index']);


Step 2: Create Controller

Next you can require to the UserController so create a UserController in just following command through.

app/Http/Controllers/UserController.php

<?php
namespace App\Http\Controllers;
use App\Models\apo_user;

class UserController extends Controller
{
    public function index()
    {
        $apo_user = apo_user::find(1);
  
        dd($apo_user->age);     
    }
}


Step 3: Create model

Next you can require to the apo_user model so create a apo_user model in just following command through.

app/Models/apo_user.php

<?php

namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Carbon\Carbon;

class apo_user extends Model
{
    protected $fillable = ['first_name', 'last_name' , 'birth_date'];
  
    /**
     * Get the user's full name.
     *
     * @return string
     */
    public function getAgeAttribute()
    {
        return Carbon::parse($this->birth_date)->age;
    }
}
php artisan serve

http://localhost:8000/function

i'm hoping it assist you to, thanks for visit my article if you like my article then proportion together with your friend and social platform.