Posted by Arjun on Saturday 28th March 2015

Laravel - Get the full name of a User using Eloquent accessors

Laravel Laravel accessors Full Name

Almost in all projects we face this situation where we have first name and last name in two different fields in the database table and we need to combine the names to show users full in the front end.For each project we implement different solution based on the Framework by fallowing DRY principles.

Here today i am gonna show you show to use laravel's Eloquent accessors for getting full name of the user.Below is example - Here is my user model, and first_name and last_name are the columns in my user table.

<?php
namespace App\Models;


class User extends Model {
	
	public function getFullNameAttribute() {
		return ucfirst($this->first_name) . ' ' . ucfirst($this->last_name);
	}

}

How to use

You can access the full name of user same of accessing other methods of user model.

$user = User::find(1);
echo $user->full_name;

or 
Auth::user()->full_name;

That's it.