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> <pre> @endif
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.
- Don’t Repeat Yourself ↩
Comments