4

I try like this :

<div class="media-body">
    @foreach($categories as $category)
    @php $category[] = $category->name @endphp
    @endforeach   
    {{ implode(",", $category) }}
</div>

If the code executed, there exist error :

undefine variable category

How can I solve it?

moses toh
  • 12,344
  • 71
  • 243
  • 443

2 Answers2

6

You can simply use Laravel Collection

{{ $categories->pluck('name')->implode(', ') }}

Or if you wanna do this in foreach then

@php ($names = [])

@foreach ($categories as $category)
    @php ($names[] = $category->name)
@endforeach

{{ implode(', ', $names) }}
Zayn Ali
  • 4,765
  • 1
  • 30
  • 40
  • It does not work. There exist error : `Missing argument 2 for Illuminate\Database\Eloquent\Model::setAttribute()...` – moses toh Jun 13 '17 at 19:40
  • I try like this : `
    @php ($category = []) @foreach($categories as $category) @php ($category[] = $category->name) @endforeach {{ implode(', ', $category) }}
    `
    – moses toh Jun 13 '17 at 19:41
  • 1
    Now it works. Because before variable array = value of foreach. Both names are the same. That's what caused the error. Thanks a lot – moses toh Jun 13 '17 at 19:50
1

You have to declare an array within <?php ... ?> block and then use the same in a {{blade}} block.

Santhosh J
  • 368
  • 3
  • 14