Search code examples
phplaravellaravel-5.3laravel-bladeimplode

How can I define variable array on the laravel blade view?


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?


Solution

  • 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) }}