Laravel Custom Getter Tutorial

Laravel 8

Nicesnippets

1806

04-05-2021


Laravel Custom Getter Tutorial

Hi guys, Today i will explained to the laravel custom getter tutorial in your laravel project.The laravel custom getter tutorial is so easy to use.so you can just follow my step by step and learn laravel custom getter tutorial.

So let's start to the example and follow to the my all step.

Solution


/**

* The attributes that are mass assignable.

*

* @var array

*/

public function getFullNameAttribute($value)

{

return $this->attributes['first_name'] . ' ' . $this->attributes['last_name'];

}

Step 1: Create a User Controller

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

app/Http/Controllers/UserController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\User;

class UserController extends Controller

{

/**

* The attributes that are mass assignable.

*

* @var array

*/

public function index(Request $request)

{

$user = User::find(1);

$fullName = $user->FullName;

dd($fullName);

}

}

Step 2: Create a User model

Last step to create a User.php models and use this code.

App/Models/User.php

<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;

use Illuminate\Database\Eloquent\Factories\HasFactory;

use Illuminate\Foundation\Auth\User as Authenticatable;

use Illuminate\Notifications\Notifiable;

class User extends Authenticatable implements MustVerifyEmail

{

/**

* The attributes that are mass assignable.

*

* @var array

*/

protected $fillable = [

'first_name',

'last_name',

'email',

'password',

];

public function getFullNameAttribute($value)

{

return $this->attributes['first_name'] . ' ' . $this->attributes['last_name'];

}

}

Step 3: Create Route

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

routes/web.php

<?php

use Illuminate\Support\Facades\Route;

use App\Http\Controllers\UserController;

/*

|--------------------------------------------------------------------------

| 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('users', [UserController::class, 'index'])->name('users');

Ok, now you have to create some dummy records on users table.

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

php artisan serve

Browser url run : http://localhost:8000/users