简体   繁体   中英

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?

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

你必须在<?php ... ?>块中声明一个数组,然后在{{blade}}块中使用它。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM