Home > Back-end >  Invalid argument supplied for foreach() - the rest is working fine
Invalid argument supplied for foreach() - the rest is working fine

Time:06-06

I'm developing a website like instagram in laravel everything was going fine until i implemented the foreach command

this is my code:

@extends('layouts.app')

@section('content')
<div >
    <div >
        <div >
            <img src="/images/simbolomax.jpg" >
        </div>
        <div >
            <div >
                <h1 >{{ $user->username }}</h1>
                <a href="/p/create">Aiciona nova receita</a>
            </div>
            <div >
                <div ><strong>153</strong> receitas</div>
                <div ><strong>23k</strong> seguidores</div>
                <div ><strong>212</strong> seguindo</div>
            </div>
            <div >{{ $user->profile->description }}</div>
        </div>
    </div>
    <div >
        @foreach($user->posts as $post)
            <div >
                <img src="/storage/{{$post->image}}"  style="height:100%">
            </div>
        @endforeach
    </div>
</div>
@endsection

and the error is: Invalid argument supplied for foreach() (View: C:\projetos\easymeal\resources\views\profiles\index.blade.php)

I can't figure out, send help!

CodePudding user response:

If there is a user with no posts... There goes ERROR. So.... Check user for posts before @foreach. @if(count($user->posts)>0).... @foreach

CodePudding user response:

Try this

@if ($user->posts->isNotEmpty())
    @foreach ($user->posts as $item)
        <div >
            <img src="/storage/{{$post->image}}"  style="height:100%">
        </div>
    @endforeach
@endif
  • Related