Get the first 2 user names

1

Let's say the name of my selected user 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 do not know if I have a facilitator or if I have to do a function manually, if I have to, can you give me some help too?

I'm currently calling this in my view: {{ Auth::user()->name }}

    
asked by anonymous 30.06.2016 / 22:46

4 answers

2

You should check if you have 2 or more names in case you only have one name, get 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 would send this from the controller.

    
30.06.2016 / 23:55
2

You can use a collection to ensure data security without having to check for something before you call 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 of the collection itself, for example:

$name = 'Rafael Henrique Berro';

$arr = explode(' ', $name);

$names = collect($arr)->slice(0, 2)->implode(' ');

// outputs: Rafael Henrique

In one line, it's confusing but it works:

$names = collect(explode(' ', Auth::user()->name))->slice(0, 2)->implode(' ');

It pays to check available methods and what a collection is in the official documentation .

    
01.07.2016 / 13:12
1

You can break the full name by the 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];

(You do not need to check if you have a spacebar in the string because you already have a last name)

    
30.06.2016 / 22:53
0

As for making the data available to the view, I'd suggest taking a look at presenters or acessors .

    
08.07.2016 / 23:42