Search code examples
laravelpatchputhttp-method

How exactly is Laravel PUT,PATCH,POST implementation?


I've been reading so many resources about the HTTP methods differences and the exact advantages As far as I got,it seems like a contract for better understanding and working with REST API. My confusion is as followings :

I have a form :

  <form action="{{ route('test') }}" method="POST">
        @csrf
        @method('PUT')
        <input type="text" name="input1" >
        <input type="text" name="input2" >
        <button type="submit">send </button>
    </form>

I have a table like this :

| id | input1 | input2 | input3

| -- | -----  | ------ |----|

| 1  |   100  |  220   |  400    

in controller I update all request fields which we sent.

  public function test(Request  $request)
    {
      return  Setting::find(1)->fill( $request->all())->save();
    }

All PUT,PATCH,POST methods worked the same way.
PUT does not change input3 to the NULL if it's supposed to regenerate resource totally. and PATCH changes input1 and input2. POST also works the same because I noted the resource ID.

the question is so what is the exact DIFF? The resources is telling us that :

create - POST
read - GET
update - PUT
modify - PATCH
delete - DELETE

while we can update,modify or even delete by using POST. when we are using form request ,the sent data is exactly the same .

We heard that PUT method regenerate resource totally , while it does not happen and it only updates the sent fields in DB( only updated Input1 and input2 in above example)
I think they will work when we are not using forms with all input and when we are sending the data partially . Are there any other deep and obvious differences in implementation ?


Solution

  • I think you have the wrong understanding of HTTP request methods. Of course, they all have differences, but not that you are pointed to.

    create - POST
    read - GET
    update - PUT
    modify - PATCH
    delete - DELETE 
    

    The lines above say you have to use a special HTTP method for a special kind of operation. Does it mean I can't use GET for deleting resources? NO, it doesn't. Technically you can use just one HTTP method with a different URL for all operations with resources. Of course, it's bad practice, but it's possible. HTTP method just shows how to send data from client to server but not how to it will be processing on server.

    So why the reasons we have to use different methods for different kinds of operations? There are some existing rules and they say: use POST for creating, PUT for updating and etc. If you create your own application, you hope it will live a long time and other developers will maintain it, and it will be much simpler to maintain your system if you stick to general rules. Also, different methods can send data with different levels of safety, and you must aware of it.