moses toh
moses toh

Reputation: 13172

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?

Upvotes: 5

Views: 27375

Answers (2)

Zayn Ali
Zayn Ali

Reputation: 4915

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

Upvotes: 7

Santhosh J
Santhosh J

Reputation: 368

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

Upvotes: 1

Related Questions