Php 如何在laravel中通过模型绑定传递变量?
我需要得到变量“type” 然后返回对象并在其他绑定中使用它Php 如何在laravel中通过模型绑定传递变量?,php,laravel,laravel-5,Php,Laravel,Laravel 5,我需要得到变量“type” 然后返回对象并在其他绑定中使用它 Route::model('key', \App\Models\Document::class, function($key) { return $objectFromFactory::where('share_key', $key)->first(); }); 毕竟,我需要设置处理请求的控制器 Route::get('share/{type}/{key}', 'ProcessShareController@shar
Route::model('key', \App\Models\Document::class, function($key) {
return $objectFromFactory::where('share_key', $key)->first();
});
毕竟,我需要设置处理请求的控制器
Route::get('share/{type}/{key}', 'ProcessShareController@share');
可能吗?或者我试图以错误的方式编写代码?这是可能的,尽管解决方案是而不是经得起未来考验的。仅当在解析逻辑中使用当前解析参数之前出现在管线中的管线参数时,此功能才起作用 当路由参数由路由器解析时,它们的处理顺序与路径中定义的顺序相同。每个已解析的参数都将添加到“管线参数”列表中 您可以通过调用
$parameters = Route::getCurrentRoute()->parameters();
您将在此处看到所有管线参数,即使某些参数尚未解析。解析之前,您将看到URL中的字符串作为其值
因此,在您的情况下,您需要以下几点:
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();
});
警告:
请记住,键参数将始终使用上述逻辑进行解析,即使路由中没有类型参数。这可能会导致错误,因为您必须始终确保,如果您定义了一个参数,那么您也定义了另一个参数
如前所述,此解决方案不是经得起未来考验的。这里的逻辑依赖于这样一个假设,即路线参数总是按照其定义的顺序进行处理。虽然我看不出未来会发生变化的原因,但也不能保证这种情况不会发生
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();
});