i am getting an error 404 not found
when accessing home.blade.php
located in resources/views
here’s the controller called postsController
<?php
namespace AppHttpControllers;
use IlluminateSupportFacadesDB;
use IlluminateViewView;
class postsController extends Controller
{
/**
*
*/
public function index(): View
{
//$posts = DB::table('posts')->get();
return view('home.index', ['users' => $posts]);
}
}
and the other file looks are
routes in web.php
Route::get('/home', [PostsController::class, 'index'])->name('home.index');
portion of codes in home.blade.php
for displaying all posts
<h1>Posts</h1>
<ul>
@foreach ($posts as $post)
<li>
{{ $post->title }} - {{ $post->body }}
</li>
@endforeach
</ul>
what’s wrong with the above code ? and how can routes be written correctly to access the desired locations? i.e home.blade.php
2
Answers
blade.php
is only to be used as a file extension for the source code of your templates, it should never really be used in your code and it should never be used by your users.home.blade.php
is not a route, that is just a template file forBlade
resources/views
is just a "source code" folder, it should never be accessed directly from the browserin your browser you would do
example.com/home
and NOTexample.com/home.blade.php
in your controller you would call the view like this
in a different controller method you might want to do something like this
class
postsController
extends ControllerRoute::get(‘/home’, [
PostsController
::class, ‘index’])->name(‘home.index’);Inconsistent controller names.
you’ve different controller name in controller file and route,it should be same, while the naming convention for controller is it should be singular and in camel case. e.g: PostController
return view(‘home.index’, [‘users’ => $posts]);
for returnig the blade file name only to return the view. e.g: ‘home’
return view(‘home.index’, [
'users' => $posts
]);you’re passing the variable names users to the view but in view you’re iterating the loop over
$post
.