Pali
Pali

Reputation: 1

Database data is not an array or object

I want to print '$post' as an array from database.

<tbody>
            @if (is_array($posts) || is_object($posts)){
                @foreach ($posts as $post)
                <tr>
                    <th>{{$post->id }}</th>
                    <td>{{$post->title }}</td>
                    <td>{{$post->body }}</td>
                    <td>{{$post->created_at }}</td>
                    <td><a href="#" class="btn btn-default">View</a><a href="#" class="btn btn-default">Edit</a></td>
                </tr>
                @endforeach

            @else
                {{'no!'}}
            @endif
            </tbody>

it just prints no! this is the main function:

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

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

Upvotes: 0

Views: 58

Answers (2)

Kuldeep Mishra
Kuldeep Mishra

Reputation: 4040

You can use get method , get will return all of the results in the model's table. After that you can pass the result to your view.

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

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

}

Upvotes: 0

AddWeb Solution Pvt Ltd
AddWeb Solution Pvt Ltd

Reputation: 21681

You should below way to pass the data from view file.

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

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

}

Upvotes: 3

Related Questions