简体   繁体   中英

Different route with different parameters to same method in laravel

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.

You want to send post and get both request to same method, if possible try this

someFunction(Request $req, $first = null, $second = null){

}

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);

    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM