Robin van der Vleuten

A package for presenting person names

When building applications, you'll probably have to show an user's name in one or more formats (first, last, initials, etc.). I've created a package called php-person-name, that will make this a lot easier in Laravel (or any PHP framework).

It is based on the name_of_person gem from the awesome people at Basecamp. They had a similar issue in their application; how do we present a person's name in different formats if we only have a first and a last name.

It's public API is quite simple and can be summarized in the following snippet.

<?php

$name = new PersonName::make('David Heinemeier Hansson')

echo $name->full // "David Heinemeier Hansson"
echo $name->first // "David"
echo $name->last // "Heinemeier Hansson"
echo $name->initials // "DHH"
echo $name->familiar // "David H."
echo $name->abbreviated // "D. Heinemeier Hansson"
echo $name->sorted // "Heinemeier Hansson, David"
echo $name->mentionable // "davidh"
echo $name->possessive // "David Heinemeier Hansson's"

Need integration with Laravel? Just use the following to add a name attribute to your models.

<?php

use Webstronauts\PersonName\PersonName;

class User extends Model
{
/**
* The attributes that are mass assignable.
*
* @var array
*/

protected $fillable = [
'name', 'first_name', 'last_name',
];

/**
* Return a PersonName instance composed from the `first_name` and `last_name` attributes.
*
* @return PersonName
*/

public function getNameAttribute()
{
return new PersonName($this->first_name, $this->last_name);
}

/**
* Sets the `first_name` and `last_name` attributes from a full name.
*
* @param string $name
* @return void
*/

public function setNameAttribute($name)
{
$fullName = PersonName::make($name);
[$this->first_name, $this->last_name] = $fullName ? [$fullName->first, $fullName->last] : [null, null];
}
}

As you can see, you'll just have to store the first_name and last_name attributes and you'll can generate all those variants through name.

<?php

$user = new User(['first_name' => 'Robin', 'last_name' => 'van der Vleuten'])

echo $user->name->full // Robin van der Vleuten

A small but nifty helper that could be useful in almost any application. Go check it out on Github and don't forget to star it.