5

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?

2
  • 1
    You must define $category[] with different name outside the @foreach loop Commented Jun 13, 2017 at 19:43
  • @smokehill, Thanks a lot Commented Jun 13, 2017 at 19:53

2 Answers 2

7

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) }}
Sign up to request clarification or add additional context in comments.

3 Comments

It does not work. There exist error : Missing argument 2 for Illuminate\Database\Eloquent\Model::setAttribute()...
I try like this : <div class="media-body"> @php ($category = []) @foreach($categories as $category) @php ($category[] = $category->name) @endforeach {{ implode(', ', $category) }} </div>
Now it works. Because before variable array = value of foreach. Both names are the same. That's what caused the error. Thanks a lot
1

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

2 Comments

Also, there's the Blade special syntax: {{--*/ $var = 'test' /*--}}. Then, you use it in the standard way: {{ $var }}.
@lesssugar, If it is variable array, it does not work

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.