Trending News Trending News -4 years ago 120
PHP Question

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
{{ implode(",", $category) }}

If the code executed, there exist error :

undefine variable category

How can I solve it?

Answer Source

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)

{{ implode(', ', $names) }}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download