Reputation: 606
I have 2 routes one for get and one for post method. For get route, i have 2 extra parameters in route, so when post method is called it says error some parameter is missing
Routes.php file,
Route::get('/abc/{one}/{two}','MainController@someFunction');
Route::post('/abc','MainController@someFunction');
Controller file,
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
}
All the code is same if i use two methods. I will get those parameters from url for get and for post i will get them from form. so code is all the same. Its redundant.
Upvotes: 1
Views: 3234
Reputation: 20469
Refactor the bulk of your method code into a 3rd private method, and call it from the two 'action' methods
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);
}
}
If the logic in doStuff
is quite long, you may want to go a step further and create a separate class to handle that logic, and inject it into the controller:
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);
}
}
Upvotes: 2
Reputation: 572
You want to send post and get both request to same method, if possible try this
someFunction(Request $req, $first = null, $second = null){
}
Upvotes: 1