php – Routes are not working, variable from controller are coming up as undefined-ThrowExceptions

Exception or error:

PostController

public function index()
{
  $posts=Post::all();
  return view('home')->with('posts', $posts);
}

web.php

Route::get('/', function () {
  return view('welcome');
});

Auth::routes();
Route::get('/home', 'HomeController@index')->name('home');
Route::resource('posts','PostController');

home

@foreach($posts as $post)
  <p>{{$post['content']}}</p>
@endforeach

I get this error

Facade\Ignition\Exceptions\ViewException

Undefined variable: posts (View: C:\xampp\htdocs\lts\resources\views\home.blade.php)

$posts are undefined

Make the variable optional in the blade template. Replace {{ $posts }} with {{ $posts ?? '' }}

Thanks for help everyone I was able to fix it by adding

Route::get('/home', 'PostController@index');  

I would love to know why this problem was caused in first place Route:: resource('posts','PostController'); should have handled it.

How to solve:

There are two ways to do this:

First One:

If you want to use HomeController for /home route then add following code in the HomeController.

HomeController:

public function index()
{
    $posts=Post::all();
    return view('home')->with('posts', $posts);
}

Second One

You have used the resource method in the web.php so your ‘PostController’ URL starts from posts But you have used /home.
So change your route like this:

In web.php

Route::get('/home', 'PostController@index')->name('home');
Route::resource('posts','PostController');

Answer:

Try this instead of what you have given for loop

@foreach($posts as $post)
    {{ $post->content}}
@endforeach

Answer:

Chnage in your controller

public function index()
    {
      $posts=Post::all();
     return view('home')->with('posts', $posts);
    }

change in your blade

@foreach($posts as $post)
    {{ $post['content'] }}
@endforeach

Answer:

Try replacing

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

with

return view('home', ['posts' => $posts]);

and

<p>{{$post['content']}}</p>

with

<p>{{ optional($post)->content }}</p>

Leave a Reply

Your email address will not be published. Required fields are marked *