7

So I am new to laravel and was just trying out some code to clear the basics,but however after creating a new controller to handle a route.It throws a fatal exception saying Class 'Controller' not found!

(The controller.php exists in the same directory)

The controller.php code is the default one

<?php

namespace App\Http\Controllers;

use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;

abstract class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
}

This is my PagesController.php code

<?php

class PagesController extends Controller
{
    public function home()
    {
        $name = 'Yeah!';
        return View::make('welcome')->with('name',$name);
    }
}

This is route.php code

<?php

Route::get('/','PagesController@home');

The welcome.blade.php code is the default one except it displays the variable $name instead of laravel 5. What am I getting wrong?

tereško
  • 58,060
  • 25
  • 98
  • 150
gospelslide
  • 179
  • 2
  • 2
  • 12

5 Answers5

10

When you reference a class like extends Controller PHP searches for the class in your current namespace.

In this case that's a global namespace. However the Controller class obviously doesn't exists in global namespace but rather in App\Http\Controllers.

You need to specify the namespace at the top of PagesController.php:

namespace App\Http\Controllers;
Limon Monte
  • 52,539
  • 45
  • 182
  • 213
  • I tried that and the controller works,but now as the namespace is the controller directory,I get an error view not found.Any other options – gospelslide Nov 19 '15 at 09:55
  • @gospelslide you can either add `use View;` to the top of controller or use alias `view` like this: `return view('welcome')->with('name', $name);` – Limon Monte Nov 19 '15 at 11:49
2

You will want to specify the namespace to your Controller class:

class PagesController extends \App\Http\Controllers\Controller

otherwise Controller is looked up in the default root namespace \, where it does not exist.

Kenney
  • 9,003
  • 15
  • 21
0

My issue was a different class name than the one in the class that extends controller, the names should be same

0

If you are creating a controller inside a subfolder with a different namespace then use this on your controller file:

use App\Http\Controllers\Controller;
PHP Worm...
  • 4,109
  • 1
  • 25
  • 48
0

In your routes/web.php, use the namespace for the PagesController eg.

<?php
  use App\Http\Controllers\Controller\PagesController;

  Route::get('/','PagesController@home');

This will enable you to access the PagesController class.