Ad
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', '[email protected]')->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', '[email protected]');
I would love to know why this problem was caused in first place Route:: resource('posts','PostController');
should have handled it.
Ad
Answer
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', '[email protected]')->name('home');
Route::resource('posts','PostController');
Ad
source: stackoverflow.com
Related Questions
- → "failed to open stream" error when executing "migrate:make"
- → October CMS Plugin Routes.php not registering
- → OctoberCMS Migrate Table
- → OctoberCMS Rain User plugin not working or redirecting
- → October CMS Custom Mail Layout
- → October CMS - How to correctly route
- → October CMS create a multi select Form field
- → October CMS - Conditionally Load a Different Page
- → How to disable assets combining on development in OctoberCMS
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → OctoberCms component: How to display all ID(items) instead of sorting only one ID?
- → In OctoberCMS how do you find the hint path?
- → How to register middlewares in OctoberCMS plugin?
Ad