Jose Garrido
Jose Garrido

Reputation: 732

Laravel routes file cannot find Controllers

I have a very simple routes.php file:

<?php

Route::get('/', 'TracksController@index');

And a simple TracksController.php file located at App\Http\Controllers:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Track as Track;

class TracksController extends Controller
{
    function index(){

        $tracks = Track::latest->get();
        return view('tracks')->with(compact('tracks'));

    }

}

But whenever I try to access that route I get this error:

ReflectionException in Route.php line 280:
Class App\Http\Controllers\TracksController does not exist

I have no idea what else I can do. I have:

But nothing seems to be working.

I even checked the vendor/composer/autoload_classmap.php file generated by composer and I cannot find the TracksController file there.

Any clues?

Upvotes: 1

Views: 7371

Answers (4)

Andrew Nolan
Andrew Nolan

Reputation: 2107

The issue lies with your $tracks = Track::latest->get();

change to $tracks = Track::latest()->get(); and you should be set.

Upvotes: 1

What I found that you must declare the use of the controller in the routes/web.php file and routes/api.php,in laravel 8 and higher ,as following: `

use Illuminate\Support\Facades\Route
use App\Http\Controllers\Controllername Route::get ('/', [ Controllername::class,'index' ]) ` for each controller for more help see the video https://www.youtube.com/watch?v=KPRV2ctCMGI

Upvotes: -1

Fernando Kosh
Fernando Kosh

Reputation: 3593

If you are using resource controllers, you must declare the use of the controller in the routes/web.php file, as following:

<?php
use App\Http\Controllers\UsersController;
...
Route::resource('users', UsersController::class);

This works here using Laravel 8.

Upvotes: -1

patricus
patricus

Reputation: 62228

If you're on linux, file names and paths are case sensitive. Assuming you haven't changed the autoloading in the default composer.json file, PHP is expecting the file to be located at app\Http\Controllers\TracksController.php. In your question, you specified it is located at App\....

Assuming this wasn't a typo in the question, you either need to rename your App directory back to app, or you need to update your composer.json file to let it know to autoload from the App directory, and not the app directory:

"autoload": {
    "classmap": [
        "database"
    ],
    "psr-4": {
        "App\\": "App/"
    }
},

Upvotes: 0

Related Questions