如何将参数传递给 Laravel 包中的控制器操作?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35071374/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I pass a parameter to a controller action within a Laravel Package?
提问by Alec Walczak
Within a Laravel package I made, I want to redirect the user to a controller action that requires a parameter (within the same package).
在我制作的 Laravel 包中,我想将用户重定向到需要参数的控制器操作(在同一个包中)。
Controller:
控制器:
public function postMatchItem(Request $request, $id)
{
$this->validate($request, [
'item_match' => 'required|numeric|exists:item,id',
]);
$spot_buy_item = SpotBuyItem::find($id);
$item = Item::find($request->input('item_match'));
$price = $item->getPrice();
$spot_buy_item_response = new SpotBuyItemResponse();
$spot_buy_item_response->spot_buy_item_id = $id;
$spot_buy_item_response->spot_buy_id = $spot_buy_item->spot_buy_id;
$spot_buy_item_response->item_id = $item->id;
$spot_buy_item_response->user_id = $spot_buy_item->user_id;
$spot_buy_item_response->spot_buy_price = $price;
$spot_buy_item_response->created_ts = Carbon::now();
$spot_buy_item_response->save();
return redirect()->action('Ariel\SpotBuy\Http\Controllers\Admin\SpotBuyController@getPart', [$id]);
}
The action in the redirect is the same path I use in my routes.php
file to direct the user to this controller action
重定向中的操作与我在routes.php
文件中用于将用户定向到此控制器操作的路径相同
Route:
路线:
Route::get('/part/{id}', 'Ariel\SpotBuy\Http\Controllers\Admin\SpotBuyController@getPart')->where('id', '[0-9]+');
I've tried variations of this path without success, including SpotBuyController@getPart
like the documentation suggests (https://laravel.com/docs/5.1/responses#redirects)
我已经尝试了这条路径的变体,但没有成功,包括SpotBuyController@getPart
文档所建议的(https://laravel.com/docs/5.1/responses#redirects)
Note: I got this to work by naming my route in routes.php
and using return redirect()->route('route_name', [$id]);
, but I still want to know how to pass a package controller action to the ->action()
function.
注意:我通过将我的路由命名为 inroutes.php
和 using 来实现这一点return redirect()->route('route_name', [$id]);
,但我仍然想知道如何将包控制器操作传递给->action()
函数。
回答by Jeff
It's trying to access your controller from within the App\Http\Controllers
namespace. Can see they've added it to your controller name in your error:
它试图从App\Http\Controllers
命名空间内访问您的控制器。可以看到他们已在您的错误中将其添加到您的控制器名称中:
App\Http\Controllers\Ariel\SpotBuy\Http\Controllers\Admin\SpotBuyController@getP??art
App\Http\Controllers\Ariel\SpotBuy\Http\Controllers\Admin\SpotBuyController@getP??art
You need to escape the Ariel
namespace with a \
at the start:
您需要在开头Ariel
使用 a转义命名空间\
:
return redirect()->action('\Ariel\SpotBuy\Http\Controllers\Admin\SpotBuyController@getPart', [$id]);