Last active
January 29, 2016 21:36
-
-
Save lagbox/915658a6bbed98be3b27 to your computer and use it in GitHub Desktop.
Extending ResourceRegistrar to allow for 'singular' wildcards and wildcard renaming.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 | |
); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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