phplaravelpsr-4

Laravel package development - Target class [ControllerName] does not exist


I'm following a tutorial on how to create laravel packages.

I'm using Laravel v8.42.1 (PHP v7.4.3) and jetstream package.

I'm stuck on creating a controller for my package, I always get following error when trying to connect to my url via the laraval app (<base-url/playground):

Target class [TestVendor\TestPackage\Http\Controllers\PlaygroundController] does not exist. 

The TestVendor\TestPackage\src\routes.php is recognized by the main application:

use TestVendor\TestPackage\Http\Controllers\PlaygroundController;
use Illuminate\Support\Facades\Route;

Route::get('/playground', [PlaygroundController::class, 'index']);

And is loaded from my ServiceProvider class:

$this->loadViewsFrom(__DIR__.'/resources/views', 'playground');
loadRoutesFrom(__DIR__.'/routes.php');

My namespacing is also normally correctly written in the composer.json of my package:

"autoload": {
    "psr-4": {
        "TestVendor\\TestPackage\\": "src/"
    }
},

And I have my PlaygroundController in src/Http/Controllers/PlaygroundController.php:

namespace TestVendor\TestPackage\Http\Controllers;

use Illuminate\Routing\Controller;

class PlaygroundController extends Controller
{

  public function index()
  {
    return view('playground::hello');
  }

}

The view is also in the right package. I'm using https://github.com/Jeroen-G/laravel-packager to scaffold my packages. Did multiple composer auto-load and composer updates.

It seems my controller is not recognized in the main application, I think somewhere my name spacing is not correct?

I already had a look at:


Solution

  • You have namespaced your controller as:

    namespace TestVendor\TestPackage\Http\Controllers;
    

    In the line above though you say:

    And I have my PlaygroundController in src/Http/PlaygroundController.php:

    Unless that is a typo, you need to add a Controllers directory underneath Http and put your PlaygroundController in there:

    src/Http/Controllers/PlaygroundController.php
    

    For psr-4 autoloading, your folder structure and namespaces should mimic each other.