0

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');
}
3
  • why can't you check like this i.e.. $posts = Post::all()->toArray(); Commented Apr 5, 2018 at 8:16
  • is ->withPosts a valid statement? Commented Apr 5, 2018 at 8:18
  • @DPS I checked it did not work, the solution was : public function index() { $posts = Post::all(); return view('posts.index',compact('posts')); } Commented Apr 5, 2018 at 8:23

2 Answers 2

3

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

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

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

}
Sign up to request clarification or add additional context in comments.

2 Comments

IT WORKED! Thank you
@Pali Glad to help you. Feel free to accept this as answer if our solution addressed your concern.
0

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'));

}

1 Comment

Thank you for this code snippet, which might provide some limited short-term help. A proper explanation would greatly improve its long-term value by showing why this is a good solution to the problem, and would make it more useful to future readers with other, similar questions. Please edit your answer to add some explanation, including the assumptions you've made.

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.