How do I use the explode to limit which parts of a string should appear in the view?

Asked

Viewed 26 times

0

I’m trying to use explode to display the first name of a resume model, in a table in the view, I was initially using the method below, but it didn’t work out the way I wanted, because it only displayed the full name of the same model in different columns. I’d like to know how to fix it in a way that fits better with what I want.

                              @foreach(explode(" ", $registro->nome) as $FirstNome)
                                <td>{{ $FirstNome}}</td>
                              @endforeach
                              @endif ``` 
  • You need to take a closer look at how the explode works, it returns a matrix... https://www.php.net/manual/en/function.explode.php

  • @Magichat got it, it’s just that in my case I’d just like to get the person’s first name, you know?

  • Which way I could do it?

  • 1

    Gives a studied in the documentation examples, makes a test in a separate script to familiarize with the function and then you implement in your code.

1 answer

0

Hello. If you only want the first name of a string, the code {{ explode(" ", $registro->nome)[0] }} should solve the problem as it takes the first value of the array returned by explode.

But I believe that there is a more elegant way of you to do this and also reuse the code in other places of the code, through direct accessors in the Model.

class Registro extends Model 
{
    public function getPrimeiroNomeAttribute()
    {
        $primeiroNome = explode(" ", $this->nome)[0];

        return $primeiroNome;
    }
}

And in the view:

$registro->primeiro_nome

Follow the official documentation: https://laravel.com/docs/eloquent-mutators#accessors-and-mutators

Browser other questions tagged

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