Laravel Custom Function In Model Example

Jun 17, 2021 . Admin

Hi Guys,

Today, In this article i will explain and share you how to use laravel custom function in model in your laravel application.So laravel custom function model easy to utilize so follow my steps.

Here,if you don't know how to make create custom function in model so don't worry i will explain you.

So,here let's started full example how to engender custom function in model easy to utilize.

Example
	public function getAgeAttribute()
	{
	    return Carbon::parse($this->birth_date)->age;
	}
Step : 1 Create Route

In this first step we will create a route in web.php file and you can use this code.

Path : routes/web.php
<?php

use App\Http\Controllers\StudentController;
use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('model-function', [StudentController::class, 'index']);
Step : 2 Create Controller

So,our next step we will require StudentController so we will create controller in following command throug.

Path : app/Http/Controllers/StudentController.php
<?php

namespace App\Http\Controllers;
use App\Models\Student;

class StudentController extends Controller
{
	/**
     * Write Your Code..
     *
     * @return string
    */
    public function index()
    {
        $student = Student::find(1);
  
        dd($student->age);     
    }
}
Step : 3 Create a Student Model

In this third step we will need to create a Student Model.

app/Models/Student.php

<?php

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

class Student 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/model-function

It will help you..

#Laravel 8 #Laravel