Connor Bishop Connor Bishop - 1 month ago 19
HTTP Question

HTTP Requests in Laravel

In Laravel we use routes to deal with HTTP requests from the browser.

We can route a request to a controller, do some logic and then return a response.

Now, we can send in variables encapsulated with braces

{}
and the response can be anything, so it seems to me that routing through a controller means that the the properties of the different request methods (POST, GET, PUT etc.) are lost.

For example I could send a POST request with URI
example/{id}
then put in my
routes.php
file

Route::post('example/{id}','SomeController@SomeAction');


Then I could do something in my controller with the variable
$id
and send a response.

On the other hand I could send a GET request with URI
example/{id}
and alter my route to

Route::get('example/{id}','SomeController@SomeAction');


The controller would give the same response.

So, am I right in thinking it does not really matter what request method is used?

Answer

Two parts of your question I can identify on a second read-through:

Request methods are not lost. You have access to them with $request->getMethod(). So a GET request will return GET. You also have the method isMethod('GET') available to you, which you could use to get a truthy value which would enable you to return a different kind of response depending on the request type.

With regards to the way you set up your URL, what HTTP verb you use does matter if you're creating a REST-ful web service.

I won't explain away what a REST-ful web service is (you can look it up), here is a couple of points from your example:

If you're getting some data, you ought to be doing a GET request. It is the verb to represent a read from a resource. If you had to send a lot of data - and your intention is to add data, you ought to POST it instead.

The URI should be meaningful in a way that best describes the resource you are manipulating.

Together with the HTTP verb, you can infer the implied action. So if you are POSTing to example/1, I might infer that (and this is a digression, actually) that you are attempting to update record 1 from an example resource. In reality, you would perhaps use the PUT verb (which handles update).

Behind the scenes, Laravel uses a POST request due to browser limitations but treats it as a PUT request server-side.