Don Boots
Don Boots

Reputation: 2166

Laravel Route::resource naming

I have the following in my routes.php

Route::resource('g', 'GameController');

I link to these generated routes via HTML::linkRoute('g.index', 'Title', $slug) which produces a link to http://domain/g/demo-slug

What I am looking to do is verify if it is possible to have the prefix be declared in one place so I'm not hunting for links if a URL structure were to change.

For example, I would want to change http://domain/g/demo-slug to http://domain/video-games/demo-slug

I was hoping to use the similar functionality with the standard routes, but that does not seem to be available to resource routes.

Route::get('/', array('as' => 'home', 'uses' => 'HomeController@getUpdated'));

Upvotes: 0

Views: 1985

Answers (3)

darronz
darronz

Reputation: 903

You can give custom names to resource routes using the following syntax

Resource::route('g', 'GameController', ['names' => [
  'index' => 'games.index',
  'create' => 'games.create',
  ...
]])

This means you can use {!! route('games.index') !!} in your views even if you decided to change the URL pattern to something else.

Documented here under Named resource routes

Upvotes: 0

David Barker
David Barker

Reputation: 14620

As far as I know it's true you can't have named routes for a resource controllers (sitation needed) but you can contain them in a common space using Route::group() with a prefix. You can even supply a namespace, meaning you can swap out an entire api with another quickly.

Route::group(array(
    'prefix' => 'video-games', 
    'before' => 'auth|otherFilters', 
    'namespace' => '' // Namespace of all classes used in closure
), function() {
    Route::resource('g', 'GameController');
});

Update

It looks like resource controllers are given names internally, which would make sense as they are referred to internally by names not urls. (php artisan routes and you'll see the names given to resource routes).

This would explain why you can't name or as it turns out is actually the case, rename resource routes.

I guess you're probably not looking for this but Route:group is your best bet to keep collections of resources together with a common shared prefix, however your urls will need to remain hard coded.

Upvotes: 1

mangonights
mangonights

Reputation: 989

Route::group() takes a 'prefix'. If you put the Route::resource() inside, that should work.

Tangent, I find this reads better:

Route::get('/', array('uses' => 'HomeController@getUpdated', 'as' => 'home'));

Upvotes: 1

Related Questions