Laravel: Controller does not exist
Asked Answered
P

15

24

I added new controller in /app/controllers/admin/ folder and added the route in /app/routes.php file as well. Then i run the following command to autoload them

php artisan dump-autoload

I got the following error

Mcrypt PHP extension required.

I followed instruction given at https://askubuntu.com/questions/460837/mcrypt-extension-is-missing-in-14-04-server-for-mysql and able to resolve the mcrypt issue.

After that i run the php artisan dump-autoload command but still getting following error

{"error":{"type":"ReflectionException","message":"Class CoursesController does not exist","file":"\/var\/www\/html\/vendor\/laravel\/framework\/src\/Illuminate\/Container\/Container.php","line":504}}

Here is code of my routes.php file

Route::group(array('before' => 'adminauth', 'except' => array('/admin/login', '/admin/logout')), function() {
    Route::resource('/admin/courses', 'CoursesController');
    Route::resource('/admin/teachers', 'TeachersController');    
    Route::resource('/admin/subjects', 'SubjectsController');
});

Here is code of CoursesController.php file

<?php

class CoursesController extends BaseController
{

    public function index()
    {
        $courses = Course::where('is_deleted', 0)->get();
        return View::make('admin.courses.index', compact('courses'));
    }

    public function create()
    {
        return View::make('admin.courses.create');
    }

   public function store()
    {
        $validator = Validator::make($data = Input::all(), Course::$rules);

        if ($validator->fails()) {
            $messages = $validator->messages();
            $response = '';
            foreach ($messages->all(':message') as $message) {
                $response = $message;
            }
            return Response::json(array('message'=>$response, 'status'=>'failure'));
        } else {
            Course::create($data);
            return Response::json(array('message'=>'Course created successfully','status'=>'success'));
        }
    }

    public function edit($id)
    {
        $course = Course::find($id);
        return View::make('admin.courses.edit', compact('course'));
    }

    public function update($id)
    {
        $course = Course::findOrFail($id);
        $validator = Validator::make($data = Input::all(), Course::editRules($id));

        if ($validator->fails()) {
            $messages = $validator->messages();
            $response = '';
            foreach ($messages->all(':message') as $message) {
                $response = $message;
            }
            return Response::json(array('message'=>$response, 'status'=>'failure'));
        } else {
            $course->update($data);
            return Response::json(array('message'=>'Course updated successfully','status'=>'success'));
        }
    }

    public function destroy($id)
    {
        Course::findOrFail($id)->update(array('is_deleted' => '1'));
        return Response::json(array('message'=>'Course deleted successfully','status'=>'success'));
    }

}
Pulling answered 19/2, 2015 at 6:23 Comment(3)
Can you please post the code located in CoursesController.phpWelford
I have added the code. This issue belongs to our staging server but it is working fine at my local systemPulling
make sure Yoy are PASSING the correct arguments to the Controller functionResponsion
S
17

Did you add autoload classmap to composer.json file? Open your composer.json file and add

"autoload": {
        "classmap": [
            "app/controllers/admin",
        ]
    }

if you add folders inside controllers, you need to add it to composer.json file. Then run

composer dumpautoload

OR ALTERNATIVE

go to app/start/global.php and add

ClassLoader::addDirectories(array(
    app_path().'/controllers/admin',
));
Sabo answered 19/2, 2015 at 7:3 Comment(7)
The problem is that other controllers of admin folders are working but only this controller is not workingPulling
try this: extends \BaseControllerSabo
It has worked by adding admin folder in global.php but my question is why it is working for other newly added controllers ?Pulling
"composer dumpautload" should have worked or you needed "composer update". Sometimes I clear out app/storage/views folder and it works.Sabo
composer dumpautoload was my problemUpali
this is worked! thanks... btw @SushantAryal do you have explanation why we need to run composer dumpautoload because i recheck my code so many times but not wrong...Unbelievable
@anunixercoder This solution is for Laravel 4. Since version 4 didn't use psr autoload, in order to reflect the changes done in composer.json you have to run composer dumpautoload. As you can see above we have added the admin directory to the controllers. Or you can use the alternative solution if you don't want to run composer dumpautoload. If you are using any version above 5 you can add any number of directory inside controllers as long as you properly namespace it.Sabo
A
13

2021 answer (Laravel 8.5)

In your controller;

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Http\Request;

class AuthController extends Controller
{
    public function login(Request $request){
        return "login";
    }
}

In your routes;

use App\Http\Controllers\AuthController;
Route::post('/login', [AuthController::class, 'login']);

Doc = https://laravel.com/docs/8.x/routing#the-default-route-files

Andriette answered 13/4, 2021 at 22:48 Comment(1)
worked, maybe accepted answere should be updatedBillionaire
P
9

In my case, in the top of my controller code i add this line :

namespace App\Http\Controllers\CustomFolder\ControllerClassName;

and my problem is solved

Peaceable answered 31/8, 2018 at 1:27 Comment(1)
This is the cause! Happens usually after you move your controller class into a directory and forget to change the namespace. Thank You! :)Competent
B
8

We can create controller via command line.

php artisan make:controller nameController --plain.

Before Laravel 5, make namespace is not available. Instead, this works

php artisan controller:make nameController

Execute your command inside your project directory and then create your function.

Briar answered 30/11, 2015 at 7:26 Comment(1)
"need" is a strong word. The make artisan commands are nothing but convenience methods, you don't need to use themDelaryd
S
8

Don't forget to do:

php artisan route:clear

In my case this was the solution when I got this error after making a route code change.

Skim answered 15/7, 2018 at 3:24 Comment(0)
M
7

In my case, I had to change the route file from this:

Route::get('/','SessionController@accessSessionData');

to this:

Route::get('/','App\Http\Controllers\SessionController@accessSessionData');

then clearing the cache with this:

php artisan route:clear

made things work.

Mallorymallow answered 29/3, 2021 at 10:38 Comment(0)
B
5

A bit late but in my experience adding this to the RouteServiceProvider.php solves the problem

protected $namespace = 'App\Http\Controllers';
Bandoleer answered 16/4, 2021 at 2:43 Comment(1)
This is a handy solution to keep optimizing the route file otherwise requires a long list of the use statements for each controller class. So, use the $namespace property and define a route path as like: Route::get('/users', 'Api\User\UserController@index');Danziger
F
3

I think your problem has already been fixed. But this is what did.

Structure

Http
  .Auth
  .CustomControllerFolder
    -> CustomController.php

to get this working in your route file make sure you use the correct name space for eg:

  Route::group(['namespace'=>'CustomControllerFolder','prefix'=>'prefix'],
      function() {

   //define your route here
}

Also dont forget to use namespace App\Http\Controllers\CustomControllerFolder in your controller.

That should fix the issue.

Thanks

Folsom answered 2/6, 2016 at 5:25 Comment(0)
C
2

I just had this issue because I renamed a file from EmployeeRequestContoller to EmployeeRequestsContoller, but when I renamed it I missed the .php extension!

When I reran php artisan make:controller EmployeeRequestsContoller just to be sure I wasn't going crazy and the file showed up I could clearly see the mistake:

/EmployeeRequestsContoller
/EmployeeRequestsContoller.php

Make sure you have the extension if you've renamed!

Crowd answered 12/10, 2016 at 8:50 Comment(0)
F
2

I use Laravel 9 this is the way we should use controllers

use App\Http\Controllers\UserController;
 
Route::get('/user', [UserController::class, 'index']);
Fremantle answered 14/4, 2022 at 13:43 Comment(0)
S
0

Sometimes we are missing namespace App\Http\Controllers; on top of our controller code.

Schuler answered 16/8, 2016 at 18:48 Comment(0)
D
0

In my case, I have several backup files of admin and home controllers renamed with different dates and we ran a composer update on top of it and it gave us an error

after I removed the other older controller files and re-ran the composer update fixed my issue.


 - Clue - composer update command gave us a warning.

Generating optimized autoload files

Warning: Ambiguous class resolution, "App\Http\Controllers\HomeController" was found in both "app/core/app/Http/Controllers/HomeController(25-OCT).php" and "app/core/app/Http/Controllers/HomeController.php", the first will be used.

Warning: Ambiguous class resolution, "App\Http\Controllers\AdminController" was found in both "app/core/app/Http/Controllers/AdminController(25-OCT).php" and "app/core/app/Http/Controllers/AdminController.php", the first will be used.
Dialyze answered 6/12, 2020 at 18:16 Comment(0)
A
0

Use full namespace inside web.php

Route::resource('myusers','App\Http\Controllers\MyUserController');
Ascus answered 30/9, 2021 at 23:28 Comment(0)
W
0

this format solves it for recent versions

   Route::post('decline', [UserController::class, 'decline'])->name('user.decline');
Witticism answered 1/7, 2023 at 10:12 Comment(0)
R
0

I've faced this issue and I figure out that I did a silly mistake in naming so to make sure you don't have any naming problems check the names in:

1- web.php or api.php

2- file nameYourController.php:

3- name of the class class YourController extends controller{}`

api.php:

use DommyController;
Route::get('dommy-route', DommyController::class, 'dommyFunction']);

DommyController.php:

use App\Http\Controllers\Controller;
class DommyController extends Controller
{
    public function index
    {
        return 'test';
    }
}

in api.php or web.php if you're using 'namespace' you should be should to use correct path of the class

Route::group([
    'prefix' => 'v1',
    'namespace' => 'Api\V1'
], function() {
   use DommyController;
   Route::get('dommy-route', DommyController::class, 'dommyFunction']);
});
Rollback answered 9/8, 2023 at 8:51 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.