fjs
fjs

Reputation: 51

Laravel: Multiple Route to Same Controller

May I know how can I make just a single route so I don't have to repeat it? Thanks in advance.

Route::get('/url', 'CtcFormController@index' )->name('CtcForm.ch');
Route::post('/url/submit', 'CtcFormController@submit')->name('CtcForm.submit');
Route::view('/url/submitted', 'form.submit')->name('CtcForm.submit');

Route::get('/url2','CtcFormController@store')->name('CtcForm.eng');
Route::post('/url2/submit', 'CtcFormController@submit')->name('CtcForm.submit');
Route::view('/url2/submitted', 'form.submit')->name('CtcForm.submit');

Upvotes: 0

Views: 1048

Answers (1)

sssurii
sssurii

Reputation: 830

As per your given example, you want to handle the variable part of the route which is /url/ and /url12/. Yes! you can handle there both different route using a single route in ways: Use route variable to handle dynamic url values i.e. url, url2,url3...url12 and so on.

Route::get('/{url}', 'CtcFormController@index' )->name('CtcForm.ch');
Route::post('/{url}/submit', 'CtcFormController@submit')->name('CtcForm.submit');
Route::view('/{url}/submitted', 'form.submit')->name('CtcForm.submit');

Now in your controller methods handing above routes receive extra parameter $url like: In controller CtcFormController.php class:

public function index(Request $request, string $url) {
       //$url will gives you value from which url request is submitted i.e. url or url12
      //method logic goes here ...
} 

Similarly, method handling /{url}/submit route will be like:

public function submit(Request $request, string $url) {
    //method logic goes here ...
}

Let me know if you have any further query regarding this or you face any issue while implementing it.

Upvotes: 1

Related Questions