23

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'));
    }

}
Community
  • 1
  • 1
Neeraj
  • 8,625
  • 18
  • 60
  • 89

15 Answers15

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',
));
Sushant Aryal
  • 3,125
  • 1
  • 25
  • 22
  • The problem is that other controllers of admin folders are working but only this controller is not working – Neeraj Feb 19 '15 at 07:07
  • try this: extends \BaseController – Sushant Aryal Feb 19 '15 at 07:17
  • It has worked by adding admin folder in global.php but my question is why it is working for other newly added controllers ? – Neeraj Feb 19 '15 at 07:33
  • "composer dumpautload" should have worked or you needed "composer update". Sometimes I clear out app/storage/views folder and it works. – Sushant Aryal Feb 19 '15 at 07:44
  • `composer dumpautoload` was my problem – insign Apr 05 '17 at 23:09
  • 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... – questionasker Jul 02 '19 at 06:23
  • 2
    @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. – Sushant Aryal Jul 07 '19 at 13:18
11

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

Akshay K Nair
  • 1,107
  • 16
  • 29
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

Baim Wrong
  • 478
  • 1
  • 10
  • 14
  • 3
    This is the cause! Happens usually after you move your controller class into a directory and forget to change the namespace. Thank You! :) – Aleksandar Jun 04 '19 at 09:51
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.

Balasubramanian
  • 5,274
  • 6
  • 33
  • 62
  • 1
    "need" is a strong word. The make artisan commands are nothing but convenience methods, you don't need to use them – Chris May 05 '20 at 14:15
6

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.

leo
  • 1,175
  • 12
  • 13
6

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.

Başar Söker
  • 606
  • 8
  • 16
5

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

protected $namespace = 'App\Http\Controllers';
Cengkuru Michael
  • 4,590
  • 1
  • 33
  • 33
  • 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');` – johirpro Jan 25 '22 at 09:14
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

usrNotFound
  • 2,680
  • 3
  • 25
  • 41
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!

haakym
  • 12,050
  • 12
  • 70
  • 98
2

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

use App\Http\Controllers\UserController;
 
Route::get('/user', [UserController::class, 'index']);
0

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

Aaron Liu
  • 151
  • 8
  • 18
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.
0

Use full namespace inside web.php

Route::resource('myusers','App\Http\Controllers\MyUserController');
DragonFire
  • 3,722
  • 2
  • 38
  • 51
0

this format solves it for recent versions

   Route::post('decline', [UserController::class, 'decline'])->name('user.decline');
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']);
});
Raskul
  • 1,674
  • 10
  • 26