Reorganizing controller files in Laravel

41 Views Asked by At

In Laravel, I can't find my controller after rearranging the file and folder structure in app/http/controller. I wanted to organize my controller files due to their large number. Here's how it looks now.

enter image description here

Then, when I want to use the following API:

Route::post('/jadwal-dokter', [DokterController::class, 'jadwaldokterterpilih']);

I'm getting this response:

Target class [App\Http\Controllers\DokterController] does not exist.

This is how I connect my api.php to my controller:

use App\Http\Controllers\DetailPasienController;
use App\Http\Controllers\dokter\DokterController;
use App\Http\Controllers\JadwalPoliController;
use App\Http\Controllers\PasienController;
use App\Http\Controllers\PoliController;
use App\Models\jadwal_poli;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

But when i change the DokterController directory to

use App\Http\Controllers\DokterController;

it can't detect my controller and it look like this enter image description here

1

There are 1 best solutions below

2
OMR On

your namespaces in the begining of the controller file should match the herirechy of the data sturcture

it should implement PSR-4 autoloading standard.

check laravel doc for more details

so namespace for DokterController should be

namespace App\Http\Controllers\dokter;

and the use should be:

use App\Http\Controllers\docker\DokterController;

further try to refactor your code in your route file . Instead of calling controller during defining each route separately you should use

 Route::controller(controllername::class)->group(function(){
     Route::get('routeurl','controllerMethodToCallForThisRoute');
})