Ad

In October Router, How To Name Endpoint, And Get URL With The Name

When I give a name to my endpoint defined in my plugin's routes.php and try to access the endpoint by browser, it throws an error showing like;

Function name must be a string
/path/to/my/src/vendor/laravel/framework/src/Illuminate/Routing/Route.php line 197

I followed the October document and it looks something like below in plugins/me/myplugin/routes.php;

Route::get(
    'api/v1/my/endpoint',
    ['as' => 'myEndpoint', 'Me\MyPlugin\Http\[email protected]']
);

On the other hand, getting the URL by the name is fine with the both ways below.

$url = Url::route('myEndpoint');

or

$url = route('myEndpoint');

Then, I tried the way described in Laravel 5.5 document, like below;

Route::get(
    'api/v1/my/endpoint',
    'Me\MyPlugin\Http\[email protected]'
)->name('myEndpoint');

Now, accessing the endpoint by browser is fine, but, getting the URL by the name gives an error.

Route [myEndpoint] not defined.
/path/to/my/src/vendor/laravel/framework/src/Illuminate/Routing/UrlGenerator.php line 305

Am I doing something wrong?

Ad

Answer

I found a workaround, which is not documented but working fine. In the routes.php define the endpoint like;

Route::name('myEndpoint')->get(
    'api/v1/my/endpoint',
    'Me\MyPlugin\Http\[email protected]'
);

Now, the endpoint is accessible and I can get URL by Url::route method and route helper.

However, I still expect those examples in my question work as well. I didn't find out what are wrong with them, yet.

FYI, naming group works as described in the October document.

Route::group(['prefix' => 'api/v1', 'as' => 'api_v1::'], function () {
    Route::name('myEndpoint')->get(
        'api/v1/my/endpoint',
        'Me\MyPlugin\Http\[email protected]'
    );
});

Then, get URL like;

Url::route('api_v1::myEndpoint');

Update (2020/02/28)

Instead of using name method, giving the name as as option like below worked, as well.

Route::group(['prefix' => 'api/v1', 'as' => 'api_v1::'], function () {
    Route::get('api/v1/my/endpoint', [
        'as' => 'myEndpoint',
        'uses' => 'Me\MyPlugin\Http\[email protected]',
    ]);
});
Ad
source: stackoverflow.com
Ad