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

Success Man picture Success Man · Jun 13, 2017 · Viewed 17.7k times · Source

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?

Answer

Zayn Ali picture Zayn Ali · Jun 13, 2017

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