Get the first 2 user names

Asked

Viewed 1,058 times

1

Let’s say my selected user name is "Raylan Soares Campos", how do I display only the first two names? In the case "Raylan Soares".

I’m using Laravel 5.2, I don’t know if you have any facilitator or if I have to do a function manually, if you have to do it can give me a help tbm?

I’m actually calling it that in my view: {{ Auth::user()->name }}

4 answers

2


Check to see if you have 2 or more names in case you only have one name, using the Klaider solution:

$names = explode(' ', Auth::user()->name); // Array ( [0] => Raylan [1] => Soares [2] => Campos )
$twoNames = (isset($names[1])) ? $names[0]. ' ' .$names[1] : $names[0];
echo $twoNames; // Raylan Soares

If I were you I’d send this from the controller.

  • But in his case it is necessary to have 2+ names. It will be unnecessary to check if there is the second name.

  • 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

  • You’re welcome @Raylansoares. Glad I could help

2

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.

1

You can break the full name by spaces contained with the function explode and then only join the first two names obtained by PHP.

/* Separa o nome pelos os espaços na string */
$arr = explode(' ', $fullName);
/* Junta os dois primeiros nomes em uma nova string */
$twoNames = $arr[0] . ' ' . $arr[1];

(no need to check if there is a space bar in the string because it is already necessary to have a last name)

0

Regarding the availability of data for the view, I suggest taking a look at presenters or accessors.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.