Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

dmcglone27's avatar

implode

How do I get each item in the array to be on it's own line when using implode with laravel? I've tried everything.

I've google and I've tried things like the following. The first, second and third one should work without a doubt.

<br />{{ $user->roles->implode('name', ',') }}
{{ $user->roles->implode('name', ',') }}<br />
<br />{{ $user->roles->implode('name', ',') }}<br />
{{ $user->roles->implode('name', ',<br />') }}
{{ $user->roles->implode('<br />', 'name') }}
0 likes
16 replies
jlrdw's avatar

Try explode and loop over array. https://www.php.net/manual/en/function.explode.php

Just example, convert to blade code:

       $roles = "a,b,c,d";
       $userroles = explode(',', $roles);
       foreach($userroles as $v){
           echo $v . "<br>";
           echo "=======" . "<br>";
       }

Output:

a
=======
b
=======
c
=======
d
=======

You use ul /li, or whatever in blade (just example only).

1 like
dmcglone27's avatar

@jlrdw Ok if you read my last answer, please disregard it. It was pre-mature. I think I might be able to do it from my Model.

dmcglone27's avatar

@jlrdw Thank you. I'm going to play around with this. Figuring out how things are done in laravel is frusturating to me at times. I guess it's safe to say, I'm still not very good at using laravel.

Snapey's avatar
Snapey
Best Answer
Level 122
{!! $user->roles->implode('name', '<br />') !!}

you need to echo raw as the output includes html

note that this is vulnerable to xss attack if users can name their own rules

3 likes
dmcglone27's avatar

@Snapey Thank you, I'll try this.

Although this is only a project to practice differeent aspects of laravel and won't be on the internet, this is only used to display the roles of each user under their picture on a page. Would that fit the bill?

dmcglone27's avatar

@Snapey Ok I just watched at video explaining xss and I believe I undstand it now and to answer your question, from what I understand from the brief video of xss, I don't have a form and I should be good because the page will only be displaying text.

jlrdw's avatar

@dmcglone27 besides implode, can you explain what it is you are trying to do? Most here from what I have seen loops over data to display things. How are you storing roles in the database.

1 like
dmcglone27's avatar

@jlrdw My goal is to learn relationships comfortabley (relationships might not be the word I'm looking for) Here's the code I have..

My Role Model. The opposite is in User

    public function roles()
    {
        return $this->belongsToMany('App\User');
    }

My Controller:

public function index()
    {
$users = User::with(['roles' => function ($query) {
            $query->where('role_name', '<>', 'members');
        }])->whereHas('roles', function ($query) {
            $query->where('role_name', '<>', 'members');
        })->get();

       return view('welcome', compact('users'));

}

My View

@foreach ($users as $user)
   <img src="/images/staff/{!! $user->img !!}"  class="rounded-circle rounded-circle-about mb-3">
   <h3>{{ $user->name }}</h3>
   <span class="position mb-5"> {!! $user->roles->implode('role_name', '<br />') !!}</span>
@endforeach

At some point I plan to use this to learn refactoring, which I originally set out to do yesterday, but my failure at this brought up other questions which I need to look up and understand before I attempt refactoring.

As for the refactoring I was thinking I can move the logic to the model and do all the computing over there so I can clean up my view. I also feel like there's a better way do the controller code, but haven't figured that out yet. Hopefully that's next on my list.

jlrdw's avatar

@dmcglone27 show what a dd($users); gives. I have never seen implode used like that in a foreach. Sounds like you just need to loop over the data and display in a ul / li tag or in a html table.

dmcglone27's avatar

@jlrdw everything always worked as expected.. What got me questioning things was when I wanted to replace the ' , ' with a "< b r / >" and the ' , ' worked fine but the "< b r / >" wouldn't.

This is what I originally had

<span class="position mb-5"> {{ $user->roles->implode('role_name', ' , ') }}</span>

This is what I changed it to because I wanted the "< b r / >" instead of the ' , '

<span class="position mb-5"> {{ $user->roles->implode('role_name', '<br /'>) }}</span>

In my mind, the above should have worked fine, but it didn't and that's what set me on the journey to figure out why it didn't work and abandoning my plan to use this code to try a refactor.

Here is the dd()... I expanded the first one so you could see the test info, but the rest are the same, but different users.

Illuminate\Database\Eloquent\Collection {#1301 ▼
  #items: array:6 [▼
    0 => App\User {#1300 ▼
      #fillable: array:3 [▶]
      #hidden: array:2 [▶]
      #casts: array:1 [▶]
      #connection: "mysql"
      #table: "users"
      #primaryKey: "id"
      #keyType: "int"
      +incrementing: true
      #with: []
      #withCount: []
      #perPage: 15
      +exists: true
      +wasRecentlyCreated: false
      #attributes: array:9 [▼
        "id" => 1
        "name" => "David McGlone"
        "email" => "david@localhost"
        "email_verified_at" => null
        "password" => ""
        "img" => "me.png"
        "remember_token" => null
        "created_at" => "2021-07-02 20:47:37"
        "updated_at" => "2021-07-02 20:47:37"
      ]
      #original: array:9 [▶]
      #changes: []
      #classCastCache: []
      #dates: []
      #dateFormat: null
      #appends: []
      #dispatchesEvents: []
      #observables: []
      #relations: array:1 [▶]
      #touches: []
      +timestamps: true
      #visible: []
      #guarded: array:1 [▶]
      #rememberTokenName: "remember_token"
    }
    1 => App\User {#1303 ▶}
    2 => App\User {#1304 ▶}
    3 => App\User {#1305 ▶}
    4 => App\User {#1306 ▶}
    5 => App\User {#1307 ▶}
  ]
}
Snapey's avatar

@jlrdw using implode here is a shorter way than a for each loop

it just takes the array and converts it to a string with a separator between each element

one thing that was confusing the op was that this was inside double curly braces which means the br tags will never be echoed correctly

1 like
jlrdw's avatar

@Snapey I see, I have only used implode to make an array a comma separated list like a,b,c etc. But either way should work.

1 like
dmcglone27's avatar

@jlrdw This is awesome, I learned when to use {!! !!} and you learned something as well. :-)

dmcglone27's avatar

I was just reading the PHP manual on implode it says

"Passing the separator after the array is no longer supported."

If this is the case, why is laravel allowing the seperator after the array in my case?

ie:

........implode('role_name', '<br />')
Snapey's avatar

This is laravel collection method implode.

1 like

Please or to participate in this conversation.