Skip to content

Instantly share code, notes, and snippets.

@bhaidar
Created October 3, 2023 07:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bhaidar/5c7e55f9c8599eb629cfa11c7374099f to your computer and use it in GitHub Desktop.
Save bhaidar/5c7e55f9c8599eb629cfa11c7374099f to your computer and use it in GitHub Desktop.
Laravel macro to split a name into a first_name and last_name
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Str;
class AppServiceProvider extends ServiceProvider
{
public function boot(): void
{
Str::macro('splitFullName', function (?string $fullName) {
$result = [
'firstName' => '',
'lastName' => '',
];
if (!$fullName) {
return $result;
}
$nameParts = explode(' ', $fullName);
$result['firstName'] = $nameParts[0] ?? '';
if (count($nameParts) > 1) {
$result['lastName'] = implode(' ', array_slice($nameParts, 1));
}
return $result;
});
}
}
@bhaidar
Copy link
Author

bhaidar commented Oct 3, 2023

Make sure to create a .stubs.php file at the root folder of your project that includes the following:

<?php

namespace Illuminate\Support
{
    class Str
    {
        public function splitFullName(string $name): array {}
    }
}

This will let your IDE catch the new method on Str::class class and provide intellisense.

Enjoy!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment