我有2条路线一条用于get,另一条路线用于post方法。 对于get route,我在路由中有2个额外的参数,所以当调用post方法时,它会说错误某些参数缺失
Routes.php文件,
Route::get('/abc/{one}/{two}','MainController@someFunction');
Route::post('/abc','MainController@someFunction');
控制器文件,
someFunction(Request $req, $first,$second){
problem is here when i use post method as there are no parameters
and this function is expecting $first and $second parameters
}
如果我使用两种方法,所有代码都是相同的。我将从url获取这些参数获取和发布我将从表单中获取它们。所以代码都是一样的。它是多余的。
答案 0 :(得分:1)
你想发送帖子并获得同样方法的两个请求,如果可能的话试试这个
someFunction(Request $req, $first = null, $second = null){
}
答案 1 :(得分:1)
将大部分方法代码重构为第3个私有方法,并从两个“action”方法中调用它
class SomeController
{
private function doStuff($first, $second)
{
//lots of
//code here
//that you dont want
//to duplicate
return $first . $second;
}
public function getSomething($first, $second)
{
return $this->doStuff($first, $second);
}
public function postSomething($request)
{
return $this->doStuff($request->first, $request->second);
}
}
如果doStuff
中的逻辑很长,您可能需要更进一步,创建一个单独的类来处理该逻辑,并将其注入控制器:
class SomeService
{
public function doStuff($first, $second)
{
return $first . $second;
}
}
class SomeController
{
protected $someService;
public function __construct(SomeService $service)
{
$this->someService = $service;
}
public function getSomething($first, $second)
{
return $this->someService->doStuff($first, $second);
}
public function postSomething($request)
{
return $this->someService->doStuff($request->first, $request->second);
}
}