Search code examples
phplaravelrouteslaravel-routing

Routes are not working, variable from controller are coming up as undefined


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.


Solution

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