Reputation: 142
I need to get variable "type"
Route::model('type', \App\Models\Document::class, function($type) {
return (new \App\Models\ShareFactory($type));
});
than return object and use it in other bind
Route::model('key', \App\Models\Document::class, function($key) {
return $objectFromFactory::where('share_key', $key)->first();
});
And after all I need to set controller that will process request
Route::get('share/{type}/{key}', 'ProcessShareController@share');
Is it possible? Or I'm trying to code in a wrong way?
Upvotes: 2
Views: 1363
Reputation: 40899
It is possible, although solution is not future-proof. This will also work only if in your resolution logic you are using route parameters that appear in the route before the parameter currently resolved.
When route parameters are resolved by Router, they are processed in the same order as they are defined in the path. Each resolved parameter is added to route parameters list.
You can access the list of already resolved parameters by calling
$parameters = Route::getCurrentRoute()->parameters();
You will see all route parameters there even if some have not yet been resolved. Before resolution you will see the string from the URL as their value.
So, in your case, you need the following:
Route::model('type', \App\Models\Document::class, function($type) {
return (new \App\Models\ShareFactory($type));
});
Route::model('key', \App\Models\Document::class, function($key) {
$parameters = Route::getCurrentRoute()->parameters();
$objectFromFactory = $parameters['type'];
return $objectFromFactory::where('share_key', $key)->first();
});
Warning: Remember that key parameter will always be resolved with above logic, even if there is no type parameter in the route. This might lead to errors, as you always have to make sure that if you define one parameter, you also define the other.
As mentioned, this solution is not future-proof. The logic here relies on the assumption, that route parameters are always processed in the order they are defined. Although I don't see a reason why it could change in the future, there is no guarantee that this won't happen.
Upvotes: 1