0

I'm beginner in Laravel and when I'm trying to use Controller I'm getting this error

Illuminate\Contracts\Container\BindingResolutionException Target class [PostsController] does not exist. http://127.0.0.1:8000/posts

routes directory contain web.php to route and there I'm using

Route::get('/posts', 'PostsController@index');

to redirect to the class PostsController

<?php
    
    namespace App\Http\Controllers;
    
    use Illuminate\Http\Request;
    
    class PostsController extends Controller
    {
        public function index() {
            echo "asdas";
        }
    }
Ameen NA
  • 39
  • 1
  • 1
  • 5

1 Answers1

1

Before diving into your problem, you should really not use Laravel 4. We are almost at version 9.

Laravel 4 lacks features, security fixes and current PHP versions support (yes, at the time of this writing, all versions < 7 shouldn't be used).

That being said, you probably have a good reason, like working on a legacy project that's hard to update.

What you could do is to use the fully qualified namespace inside your route file.

Route::get('/posts', '\App\Http\Controllers\PostsController@index');

Also, triple check that you are using Laravel 4. The problem you have could also be caused by one of the latest Laravel update (version 8) where the default namespace was removed from the App\Providers\RouteServiceProvider file.

If you made a mistake and you are on Laravel 8, then just use the following notation:

Route::get('/posts', [\App\Http\Controllers\PostsController::class,'index']);

[EDIT]

As mentioned in the comments, you could also uncomment // protected $namespace = 'App\\Http\\Controllers'; in your route file. Of course, this apply to Laravel 8 so if you are on Laravel 4, just ignore this edit.

Anthony Aslangul
  • 3,589
  • 2
  • 20
  • 30
  • 1
    For a quick fix on existing applications with a lot of routes, you can re-add the default namespace. (I use that solution currently, and change all the routes to the new syntax while I make changes to the applications) – Gert B. Aug 24 '21 at 06:36