Laravel Custom Function In Model

10-Apr-2023

.

Admin

Laravel Custom Function In Model

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...

#Laravel 8

#Laravel 7

#Laravel

#Laravel 6