How to fix ‘Target class does not exist’ in Laravel 8

How to fix ‘Target class does not exist’ in Laravel 8

https://ift.tt/2E5om9N


How do I fix this?

The problem here is that Laravel has no idea where to look for your controller, so all we have to do is let it know! There are 3 ways you can accomplish this:

  • Add the namespace back manually so you can use it as you did in Laravel 7.x and before
  • Use the full namespace in your route files when using the string-syntax
  • Use the action syntax (recommended)

Adding the namespace manually

This is fairly simple. Go into your RoutesServiceProvider.php file and you’ll see the following:

All you need to do is add the following three lines to this file and Laravel will go back to using the default namespace as in Laravel 7.x:

What did we just do? We declared the $namespace variable with the default Namespace for our controllers and told laravel to use that for our web and api routes.

If you try to run your app again, everything should be working.

Using the full namespace

This one involves changing all your route declarations, but the idea is simple: prepend your controller names with their namespace. See the following example for our PostsController inside the app/Http/Controllers folder.

If you try again, everything should be running smoothly.

Using the Action Syntax

This is the alternative I personally recommend as I find it more typo-proof and in my experience provides better IDE support as we are explicitly telling the code which class to use. Instead of using our usual string syntax, we can use the action syntax where we specify the class and method to use in an array:

Notice here we are not passing the PostsController within quotes but rather PostsController::class, which internally will return ‘App\Http\Controllers\PostsController’. The second value in the array is the method to call within that controller, meaning: “In PostsController.php call the ‘all’ method.

Again, if you try to run your app again, everything should be up and running.

Closing Remarks

By now, your app should be up and running again. If not, please feel free to ask for help. Everyone in the community is eager to give a hand.

Whether you added the namespace manually, specified the full namespace in your routes, or went with the action syntax, what you just did is tell Laravel in which namespace your controllers actually are, so now it actually knows where to look.

If you liked what you read or want to learn more cool stuff related to Laravel, you can follow me on Twitter, where I post about coding, entrepreneurship, and living a better life.

programming

via Laravel News Links https://ift.tt/2dvygAJ

September 15, 2020 at 08:15PM