ventaquil ventaquil - 5 months ago 79
PHP Question

Laravel package controller alias in routes

I'm trying to create package in Laravel 5.2 with routes. I have controller in

Http/Controllers
folder (with namespace
vendor\package\Http\Controllers\MyController
). I want to create alias but I don't know how. I don't want to call this controller in
routes.php
like that:

Route::get('myurl', vendor\package\Http\Controllers\MyController::class . '@action');


But like that:

Route::get('myurl', 'MyController@action');


I tried to search this in
Application
class API but I can't find this information.

This code in package provider doesn't work.

$this->app
->alias(vendor\package\Http\Controllers\MyController::class, 'MyController');


My service provider:

class PackageRouterServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
//
}

/**
* Register the application services.
*
* @return void
*/
public function register()
{
include(__DIR__ . '/../Http/routes.php');

$this->app->alias(MyController::class, 'MyController'); // <- I tried this
}
}

Answer

Try to update your PackageRouterServiceProvider.php like this:

class PackageRouterServiceProvider extends ServiceProvider
{
    // Set this namespace to your package controllers namespace.
    protected $namespace = 'vendor\package\Http\Controllers';

    public function boot(Router $router)
    {
        //
    }

    public function register()
    {
        $this->mapRoutes($this->app->router);
    }

    protected function mapRoutes(Router $router)
    {
        $router->group(['namespace' => $this->namespace], function($router) {
            require (__DIR__ . '/../Http/routes.php');
        });
    }
}

Of course, then you need to register this provider in your Laravel config app.php file in order to work.