Skip to content

Instantly share code, notes, and snippets.

@lagbox
Last active January 29, 2016 21:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lagbox/915658a6bbed98be3b27 to your computer and use it in GitHub Desktop.
Save lagbox/915658a6bbed98be3b27 to your computer and use it in GitHub Desktop.
Extending ResourceRegistrar to allow for 'singular' wildcards and wildcard renaming.
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
//
}
/**
* Register any application services.
*
* @return void
*/
public function register()
{
$this->app->bind(
\Illuminate\Routing\ResourceRegistrar::class,
\App\Lib\ResourceRegistrar::class
);
}
}
<?php
namespace App\Lib;
use Illuminate\Routing\ResourceRegistrar as BaseRegistrar;
class ResourceRegistrar extends BaseRegistrar
{
protected $wildcards = [];
/**
* Format a resource wildcard for usage.
*
* @param string $value
* @return string
*/
public function getResourceWildcard($value)
{
$wildcard = parent::getResourceWildcard($value);
if (! is_array($this->wildcards) && $this->wildcards == 'singular')
return str_singular($wildcard);
return isset($this->wildcards[$wildcard]) ?
$this->wildcards[$wildcard] : $wildcard;
}
/**
* Route a resource to a controller.
*
* @param string $name
* @param string $controller
* @param array $options
* @return void
*/
public function register($name, $controller, array $options = [])
{
if (isset($options['wildcards']))
$this->wildcards = $options['wildcards'];
parent::register($name, $controller, $options);
}
}
<?php
// because why not
Route::group(['middleware' => 'web'], function () {
Route::resource('users', 'UserController', ['wildcards' => 'singular']);
Route::resource('users.photos', 'PhotoController', ['wildcards' => 'singular']);
// or this for different wildcard names
Route::resource('users.photos', 'PhotoController', ['wildcards' => [
'users' => 'person', 'photos' => 'image'
]])
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment