Laravel: user “display name”, or first + last name

When it comes to names you need to account for some people having only one name instead of a first name/surname, you need to account for the fact that some cultures put the family name before the ‘given’ name.

In the current web app I’m building we’ve decided to give people the option to set a “Display Name” so we can collect their full name but give the user control over the display of their name.

I’m building this web app using the awesome Laravel and I am learning at high-speed. In the spirit of DRY1, I wanted to make sure that when I retrieved the user’s name to display in any view I wouldn’t have to repeat checking whether they had a display_name set or not.

Here’s how I went about it. If there are better ways to do this, I’m all ears.

In the User model

class User extends Eloquent
    public function name()
		if ($this->name_display) {
			return $this->name_display;
		} else {
			return $this->name_first . ' ' . $this->name_last;

In a controller

In this example below one of my controller actions has already retrieved the User and I can easily get the name.

$name = User::find($user->id)->name();

In a master template

Elsewhere in the site I’ve got a master template layout that displays a welcome message if the user is logged in.

@if ( !Auth::guest() )</pre>
<h3>Welcome {{Auth::user()->name()}}</h3>

I’m very much open to any other approaches for doing this as I’m very much just dipping my toe in the pond.

Thanks to nickstr on Laravel IRC for pointing me in the right direction.

  1. Don’t Repeat Yourself


  • One way to do this differently would be to use a getter.

    public function get_display_name()
    return “$this->first_name $this->last_name”;

    You can access it without parenthesis as: $user->display_name

    Another way to do it would be to use a presenter layer like or

    • Thanks Shawn – I’ll check those options out over the weekend 🙂

    • By the way, I had planned to read your book from start to finish, but I’ve actually been using it more as a reference guide as I needed to get stuck into something.. going to eh, learn by shipping or something!

    • For the time being I think I’ll stick with the getter. I had a quick look over the presenter layer and it looks cool, but I’ll have to check it out in more depth later in the week.

  • Jeff Simons Decena

    How about like this?

    public function __construct() {
    $user = User::find(Auth::id());
    View::share(‘name’, $user->firstname);
    $this->layout = ‘tpl.main’;

    Then at the tpl main tpl file. Just call {{ $name }}