Forest
Forest

Reputation: 938

Using a different controller for GET and POST in Laravel but using the same name

I am writing route and controller rules for a web application. In a number of rules, a problem has emerged, which is that I need to match both GET and POST verbs, and send them to the controller, but different methods.

I considered using Route::controller('tracking', 'TrackingController') for this, but then it requires different names for each internal route, whereas I want to specify one name for both. Besides, I've read nothing but negativity regarding the usage, suggesting that it is not a good idea.

Here's what I have currently:

Route::match(['get', 'post'], '/tracking', [
    'as' => 'tracking',
    'uses' => 'TrackingController@index'
]);

While implementing this, I have discovered that I need to have two controller methods, index and track. How can I efficiently route GET to index and POST to track, while maintaining the same controller (TrackingController) and the same name (tracking)?

I considered using two separate routes, e.g. Route::get and Route::post, but that doesn't feel very eloquent.

Upvotes: 1

Views: 782

Answers (1)

Imtiaz Pabel
Imtiaz Pabel

Reputation: 5443

you can use easily Route Controller,like this

Route::controller('tracking', 'TrackingController')

In here if you wanna use same method for both get and post,just use any prefix in method,like

//for both get and post
public function anyUrl();
//only get
public function getUrl();
//only post
public function postUrl();

Or use

Route::any('/url', function () {
return 'Hello World';
});

Upvotes: 1

Related Questions