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.
1 2 3 4 5 6 7 8 9 10 11 |
<?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.
1 2 3 4 5 |
$user = User::find(1); echo $user->full_name; or Auth::user()->full_name; |
That’s it.
I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.
Thanks, worked great (Laravel 6)