Lestah
Lestah

Reputation: 53

ErrorException Invalid argument supplied for foreach() Laravel

I'm just trying to get all the data from my table name posts but an error occur it wont let me display the data on my index.blade.php

public function index()
    {
        //
        $posts = Post::all();

        return view('posts.index')->withPosts('$posts');

    }

and here's my index.blade.php

@foreach( $posts as $post )
            <div class="post-preview">
                    <a href="post.html">
                        <h2 class="post-title">

                            {{ $post->title }} -> this is the one i want to display

                        </h2>
                        <h3 class="post-subtitle">

                            {{ $post->body }}

                        </h3>
                    </a>
                    <p class="post-meta">Posted by <a href="#">Start Bootstrap</a> on September 24, 2014</p>
                    <button type="button" class="btn btn-secondary">&nbsp;&nbsp;Edit&nbsp;&nbsp;&nbsp;</button>
                    <button type="button" class="btn btn-secondary">Delete</button>
            </div>

                <hr>
            @endforeach

Upvotes: 1

Views: 16280

Answers (5)

schutte
schutte

Reputation: 2166

If the other solutions were not working, try this.

I may think that you just missed this single line "enctype="multipart/form-data" in your form.

See example below:

<form action="{{ route('upload.files') }}" method="POST" enctype="multipart/form-data">
<input id="fileupload" type="file" name="attachment[]" multiple>
</form>


Don't forget to click the arrow up. I hope I did help you :)

Upvotes: 0

Ramzan Mahmood
Ramzan Mahmood

Reputation: 1901

You should use it as

return view('posts.index')->with(compact('posts'));

Upvotes: 1

Dharmesh Rakholia
Dharmesh Rakholia

Reputation: 1238

You can use compact method

return view('posts.index',compact('posts'));

Upvotes: 0

Vishal Varshney
Vishal Varshney

Reputation: 905

not use single quote in $posts

return view('posts.index')->withPosts($posts);

or try second way as

return view('posts.index', compact('posts'));

Upvotes: 0

Amarnasan
Amarnasan

Reputation: 15579

You'd better use with like this:

return view('posts.index')->with('posts',$posts);

Upvotes: 1

Related Questions