Created
October 3, 2023 07:23
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?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; | |
| }); | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Make sure to create a
.stubs.phpfile at the root folder of your project that includes the following:This will let your IDE catch the new method on
Str::classclass and provide intellisense.Enjoy!