Skip to content

All topics  /  Laravel

Laravel Custom Function In Model

Laravel ·

Teams applying “Laravel Custom Function In Model” in a production project can use continuous partial attention to record implementation, review and debugging time, then compare that effort with tests and shipped functionality instead of treating activity as performance by itself.

Before copying the example into a live application, confirm version-specific behaviour with the official Laravel website and test it against the project’s actual database and runtime.

Hi guys,

Today i will explained to the How to use Laravel Custom Function In Model in your laraval project.Laravel Custom Function In Model is so easy to use.so you can just follow my step by step and learn Laravel Custom Function In Model.

if you want to see example of laravel create custom function in model then you are a right place.you can see laravel model call function.

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

So let's start to the example and follow to the 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 a UserController

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 a apo_user 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;
    }
}

So, finally we are done with our code we can get below output.

php artisan serve
http://localhost:8000/function

It will help you...