I have the following routes in routes/api.php:
Route::get('items/{item}', function(Guid $item) {...});
Route::get('users/{user}', function(Guid $user) {...});
Since Guid is a custom type, how can I resolve that via dependency injection? As shown, the route parameter {item} differs from the callback parameter type-hint:Guid so it can not be automatically resolved.
That's what I've tried in app/Providers/AppServiceProvider.php:
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* @return void
*/
public function register()
{
$this->app->bind(Guid::class, function(Application $app, array $params) {
return Guid::fromString($params[0]);
});
}
}
I'd expect $params to be something like this: [ 'item' => 'guid' ] -- but it is: [].
You can make use of explicit binding Laravel Routing:
in
RouteServiceProvider::boot():If
Guidis not a model use a Closure to map onto the string:UPDATED
And I found another way, much better - implement UrlRoutable contract Lavaravel API:
And, with this, you can use routes like you want as
Guidnow implementsUrlRoutableand can turn{item}(or whatever) URL-path sub-string markers into Guids per dependency injection (by the type-hint as you asked for it):