Laravel 5 class inheritance
I am working with laravel 5 code.
I cannot extend a class that has a different namespace than the child.
My parent class Folder is App / Http / Controllers /
namespace App\Http\Controllers;
use Illuminate\Routing\Controller as BaseController;
class MainController extends BaseController{
function __construct() {
}
function home() {
echo "main";
}
}
And my class child Folder is App / Http / Controllers / Site
namespace App\Http\Controllers\Site;
class SiteController extends MainController {
function __construct() {
parent::__construct();
}
function home() {
return view('dashboard');
}
}
And my routes file has this route
Route::get('/', 'Site\SiteController@home');
This is the error I am getting
FatalErrorException in SiteController.php line 5: Class 'App\Http\Controllers\Site\MainController' not found
This is clearly a namespace problem, because when I do
Route::get('/', 'Site\SiteController@home');
This is the echos home method in MainController
How do I get this to work?
+3
source to share
1 answer
This is not a Laravel 5 issue, but a general PHP namespace issue.
There are two ways to achieve this:
- use
use
statement: add this lineuse \App\Http\Controllers\MainController;
- use the full namespace: change your line to
class SiteController extends \App\Http\Controllers\MainController
Choose the method you like best.
+3
source to share