Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5.2 Split String First Name Last Name

I have a string passed from a form which is full name.

in my database I store first name and last name.. I've split the string using the following:

$name = explode(" ", $request->name);
$lastname = array_pop($name);
$firstname = implode(" ", $name);

this works great, however, if the user doesn't enter a surname in the field then the above doesn't work as the lastname becomes the first.

Am I missing something?

like image 763
Dev.W Avatar asked Jul 08 '16 13:07

Dev.W


People also ask

How do I search first name and last name in laravel query?

$query->where(function ($q) use ($columns, $value) { foreach ($columns as $column) { $q->orWhere($column, 'like', "%{$value}%"); } });

How to split name in Laravel?

I've split the string using the following: $name = explode(" ", $request->name); $lastname = array_pop($name); $firstname = implode(" ", $name); this works great, however, if the user doesn't enter a surname in the field then the above doesn't work as the lastname becomes the first.


1 Answers

This is what I've used for splitting names:

$splitName = explode(' ', $name, 2); // Restricts it to only 2 values, for names like Billy Bob Jones

$first_name = $splitName[0];
$last_name = !empty($splitName[1]) ? $splitName[1] : ''; // If last name doesn't exist, make it empty
like image 68
aynber Avatar answered Sep 28 '22 20:09

aynber