Fabian Michael
Fabian Michael

Reputation: 5

Why do I have to get this error so often?

Hello World!

I have a small issue and I don't know how to solve it. I tried some things but nothing worked. The error looks like this:

Undefined variable: post (View: ../resources/views/blog/posts/index.blade.php)

This is my code in the controller:

<?php

public function index() {
    $posts = Post::orderBy('created_at','ASC')->paginate(15);
    return view('blog.posts.index')->withPosts($posts);
}

public function post($slug) {

    // Fetch from the database based on slug.
    $post = Post::where('slug', '=', $slug)->first();

    // Return the view and pass the post object.
    return view('blog.posts.post')->withPost($post);
}

And that's a part of the code for view:

<!-- Main Content -->
<div class="container" id="load-data">
  <div class="row">
    <div class="col-lg-8 col-md-10 mx-auto">
      @foreach($posts as $post)
      <div class="post-preview">
        <a href="{{ url('blog/posts/'.$post->slug) }}" role="button">
          <h2 class="post-title">
            {{ $post->title }}
          </h2>
          <h3 class="post-subtitle">
            {{ $post->desc }}
          </h3>
        </a>
        <p class="post-meta">Posted on {{ date('F j, Y', strtotime($post->created_at)) }}</p>
      </div>
      <hr> @endforeach
    </div>
  </div>
</div>

And also the route:

Route::prefix('/blog/posts')->group(function () {

Route::get('/', 'BlogController@index')->name('posts'); });

Thank you for your answers!

Upvotes: 0

Views: 37

Answers (1)

Joshua McNabb
Joshua McNabb

Reputation: 98

Laravel has two main ways of sending data (variables) from the Controller to the View. The first way, as outlined in their documentation (https://laravel.com/docs/5.8/views) is by chaining with to the view function.

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

You can chain with as much as you want, however this isn't very clean if you need to send lots of variables to the view. The more accepted way to do this is by using PHP's compact function (https://www.php.net/manual/en/function.compact.php) as the second parameter of the view function, as @Ben96 pointed out. compact essentially converts a string of variable names to an associative array with their keys and values, which allows them to be used in the view.

Upvotes: 1

Related Questions