Skip to content

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

Last updated on December 2, 2022

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

Here today I am gonna show you how to use Laravel’s Eloquent accessors for getting the full name of the user. Below is an example – Here is my user model, and first_name and last_name are the columns in my user table.

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 the user the same as accessing other properties of the user model.

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

or 
Auth::user()->full_name;

That’s it.

3.5 2 votes
Article Rating
Subscribe
Notify of
guest

1 Comment
Most Voted
Newest Oldest
Inline Feedbacks
View all comments