Tropicalista
Tropicalista

Reputation: 3137

Laravel package Controller not found in route

I have a simple package and I want to use the controller. When I try to use it in routes I got

Class App\Http\Controllers\Tropicalista\Admin\Controllers\DashboardController 
does not exist

I have this in my /routes/web.php

Route::group([
    'namespace' => '\Tropicalista\Admin\Controllers', 
    'prefix'=> 'admin'], function() {

        Route::get('/', ['as' => 'admin.root', 'uses' => 'DashboardController@index']);

});

My controller:

namespace Tropicalista\Admin\Controllers;

use Illuminate\Http\Request;
use Analytics;
use Carbon\Carbon;
use Spatie\Analytics\Period;
use Illuminate\Support\Collection;
use Illuminate\Routing\Controller;

class DashboardController extends Controller
{...}

I think is a namespace problem. So how can I call the package controller?

Upvotes: 2

Views: 1484

Answers (3)

Kisz Na
Kisz Na

Reputation: 482

In order to call package controller, change the namespace group of RouteServiceProvider from

protected $namespace = 'App\Http\Controllers';

to null/empty i.e.

protected $namespace = '';

Then, the route can be written as,

Route::get('homepage', 'Package\Namespace\Controllers\ControllerName@ActionName');

Further, if you want to write route for the default controller, use leading slash '/' before starting url.

Route::get('/homepage', 'App\Http\Controllers\ControllerName@ActionName');

Whether it is good practice or not but it solved the problem.

Upvotes: 1

Alexey Mezenin
Alexey Mezenin

Reputation: 163978

Since it's a package, you need to register the routes in the package.

You can see an example of registering package controllers here:

$routeConfig = [
    'namespace' => 'Barryvdh\Debugbar\Controllers',
    'prefix' => $this->app['config']->get('debugbar.route_prefix'),
    'domain' => $this->app['config']->get('debugbar.route_domain'),
    'middleware' => [DebugbarEnabled::class],
];
$this->getRouter()->group($routeConfig, function($router) {
    $router->get('open', [
        'uses' => 'OpenHandlerController@handle',
        'as' => 'debugbar.openhandler',
    ]);
});

Upvotes: 1

Sohel0415
Sohel0415

Reputation: 9863

By default, the RouteServiceProvider includes your route files within a namespace group, allowing you to register controller routes without specifying the full App\Http\Controllers namespace prefix. So, you only need to specify the portion of the namespace that comes after the base App\Http\Controllers namespace.

You need to remove namespace

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

    Route::get('/', ['as' => 'admin.root', 'uses' => '\Tropicalista\Admin\Controllers\DashboardController@index']);

});

Upvotes: 5

Related Questions