skip to Main Content

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


  1. 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 for Blade

    resources/views is just a "source code" folder, it should never be accessed directly from the browser

    in your browser you would do example.com/home and NOT example.com/home.blade.php

    in your controller you would call the view like this

    // 'home' is the name of the view
    return view('home', ['posts' => $posts]);
    

    in a different controller method you might want to do something like this

    // 'home.index' is the name of the route
    return redirect()->route('home.index'); 
    
    Login or Signup to reply.
  2. class postsController extends Controller

    Route::get(‘/home’, [PostsController::class, ‘index’])->name(‘home.index’);

    1. 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

    2. return view(‘home.index’, [‘users’ => $posts]);
      for returnig the blade file name only to return the view. e.g: ‘home’

    3. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search