Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

jay_gorio's avatar

How to combine firstname lastname and middlename

How do I combine firstname, lastname and middename and to display them as fullname .

0 likes
27 replies
mstnorris's avatar

@jearson Write a function to concatenate them. If you're talking about your User model, then do something like:

public function fullName() {
    return $this->firstName . ' ' . $this->middleName . ' ' . $this->lastName;
}

Then when accessing a User, you can use:

$user->fullName();

You'll have to take care of logic to allow for null middle names etc otherwise you'll end up with two spaces in-between the firstName and lastName values.

1 like
zachleigh's avatar

This is very basic php...

$firstname = 'Bob';
$middlename = 'Frank';
$lastname = 'Smith';

$fullname = $firstname . ' ' . $middlename . ' ' . $lastname;
mstnorris's avatar

@ModestasV that doesn't at all explain how to join the names? Accessors and Mutators are primarily for accessing and mutating single fields. Here, we are potentially combining three.

Giolf's avatar

@ModestasV i'm not a big fun of them, especially if you need to use them for rendering view (just show data), and in the forms (for edit the same data).
I prefer to write my own function in the model.

ModestasV's avatar

@mstnorris @Giolf yes, you can do it with mutators. Mutators are not called per field. Well technically they are but you are free to access another field via mutator.

public function setNameAttribute($value)
{
    $this->attributes['Name'] = $value.$this->SubName;
}

I've used this code and it worked fine :)

Amrit01's avatar

In your user model add this function.

     /**
     * Get the user's full name.
     *
     * @return string
     */
    public function getFullNameAttribute()
    {
        return preg_replace('/\s+/', ' ',$this->first_name.' '.$this->middle_name.' '.$this->last_name);
    }

Usage :

$user = User::find(1);
echo $user->full_name;
7 likes
sebastiansulinski's avatar

What I'd probably do is to use implode() and array_filter function to make sure that if any of the properties / fields is empty - it's excluded from the concatenation - something like:

public function getFullNameAttribute()
{
    return implode(
        ' ',
        array_filter(
            [
                $this->first_name,
                $this->middle_name,
                $this->last_name
            ],
            function($item) {

                return ! empty($item);

            }
        )
    );
}
3 likes
Prullenbak's avatar

@Amrit01 is right.

You could only improve it a little bit, by checking if there is a middlename before you add it with the extra space. Just so you don't end op with firstname[space][space]lastname. Double spaces won't be a problem if you only use it in your html views, but otherwise it might be better to return a proper full name.

Prullenbak's avatar

Well, yes you can, but then you'd have to do that everywhere you use the last_name attribute. I think it would be a bit better to just return it properly from the getFullNameAttribute() method. But this was just a tiny detail. The main takeaway is: use accessors and mark @Amrit01 's answer as correct ;)

bestmomo's avatar

I think it depends on context. For example why get first name, middlename and last name if he only wants the cancatened version ? In this case a SQL concatenation should be better than an accessor.

pmall's avatar

In this case a SQL concatenation should be better than an accessor.

For what reason ? For readability concerns accessor is better. Here you have to tweak a sql query somewhere.

1 like
bestmomo's avatar

For readability concerns accessor is better

I dont see why an eloquent accessor is more readable than a good SQL query.

Prullenbak's avatar

A SQL concatenation? Why?

If he's getting the user from the database with eloquent, the firstname, middlename and lastname are already fetched from the database in a single SELECT * FROM users WHERE id = 1 query. Then, it makes way more sense to just let PHP generate a fullname from that data. Why would you make your queries more complicated? I wouldn't even know how to make eloquent do a SELECT *, concat([some stuff here]) as full_name FROM users by default. And then: it would do it even in the situations where php doesn't even need the full_name.

So again: why?

1 like
bestmomo's avatar

@Prullenbak

You say that Eloquent already get all fields from database. So I again I say it depends on context. A concat select is not complicated, you only have to add a selectRaw in the query and it's done and it's SQL engine that does the stuff.

Prullenbak's avatar

you only have to add a selectRaw in the query

Again: why would you add all kind of custom, more complicated raw database stuff, and where would you do that? Would you make eloquent do that by default on every query (I don't know how to do that, but you probably can)? Then, it would perform this query every time, even if you don't need the full name for that request.

I think you're making this way too complicated, while there already was a nice, elegant, good answer to the question. You keep saying "it depends on context" and that's, off course, always true. But in this case (the case we're talking about in this thread) I don't see a reason to do it any other way than to use a simple accessor.

bestmomo's avatar

@Prullenbak

I dont really see the complicated aspect. Says you want a listing of users with full name. You can use this simple query :

$users = User::selectRaw("CONCAT(firstname, ' ', lastname) as fullName")->get();

It's for me clearer than doing :

// In user model :
public function getFullNameAttribute()
{
    return $this->firstname . ' ' . $this->lastname;
}

// And query :
$users = User::select('firstname', 'lastname')->get();
Prullenbak's avatar

No, it's totally not clearer than that. Because with the latter, you can use it on any user model so you can do:

Auth::user()->full_name;

or, suppose you have a post model with a relation to users:

$post = Post::with('author')->findOrFail($id);
$post->author->full_name

and you don't have to think about doing your raw custom stuff everytime. You just know there is a user object, so you can get the full name, if you want. No extra queries required. Ever.

In your example:

$users = User::select('firstname', 'lastname')->get();

that's totally unnecessary. Just do $users = User::all();

It really seems like you're making this more complicated than it really is.

2 likes
bestmomo's avatar

As I said before it depends on context, my isolated example is correct, your extended one is also correct because you say you need full name on any user and not only on listing one.

Amrit01's avatar

i have updated my answer to strip white spaces .just do it however u like . there is nothing better

pmall's avatar

Totally agree with @Prullenbak his examples are perfect. From my experience using eloquent, the less you play with sql, the happier you are. It really need to be a big performance improvement (ex: eager loading a related count) to worth writing custom sql.

mnrafg's avatar

/**
 * Get the user's full name.
 *
 * @return string
 */
public function getFullNameAttribute()
{
    return sprintf('%s %s %s',
        $this->first_name,
        $this->middle_name,
        $this->last_name
    );
}

Usage


<li> {{ $user->full_name }} </li>

4 likes

Please or to participate in this conversation.