You can use a collection to ensure data security without having to check if something exists before calling it. For example:
$name = 'Rafael Henrique Berro';
$arr = explode(' ', $name);
$collection = collect($arr);
$firstname = $collection->shift();
$lastname = $collection->shift();
// outputs: Rafael Henrique
You can also choose to use other methods from the collection itself, for example:
$name = 'Rafael Henrique Berro';
$arr = explode(' ', $name);
$names = collect($arr)->slice(0, 2)->implode(' ');
// outputs: Rafael Henrique
In a row, confusing but works:
$names = collect(explode(' ', Auth::user()->name))->slice(0, 2)->implode(' ');
It is worth checking out the available methods and what is a collection on official documentation.
But in his case it is necessary to have 2+ names. It will be unnecessary to check if there is the second name.
– Klaider
Actually there is no specific number, the user may actually have 1 or 2, 5, anyway, I think better to check even, thanks to the 2
– Raylan Soares
You’re welcome @Raylansoares. Glad I could help
– Miguel