What is method spoofing in Laravel?

In this article we will discuss about method spoofing in Laravel. But first of all we will know about HTTP method.

HTTP Methods

HTTP defines a set of request methods. Through the HTTP request method we can take action on any resource of the server. In other words, the purpose of the HTTP request is to access the server’s resources.

Different HTTP Methods

The following are five common HTTP methods:

GET is used to access resources that are located at the specified URL.
POST is used to send data to the server. Commonly used for adding new records.
PUT is used to update existing resources on the server.
PATCH method is used to partial update to a resource and can be considered as a lightweight option to PUT.
DELETE is used to remove the resource.

Method Spoofing in Laravel

In Laravel we can define routes in web routes pointing to POST, PUT, PATCH, or DELETE methods.

We know that HTML forms do not support PUT, PATCH, or DELETE actions. So now the question is how to call our defined PUT, PATCH or DELETE routes from the HTML form?

Through method spoofing in Laravel, HTML forms can point to POST, PUT, PATCH, or DELETE routes that are defined in the web routes. For that, It is needed to add a hidden field of name _method to the form to support PUT, PATCH, or DELETE actions. The value of this hidden field should be the method name i.e. PUT, PATCH etc .

In this way, adding the name of the method to the HTML form through the hidden field and calling methods that do not support HTML is called Laravel method spoofing.

The @method Blade directive or method_field function generates an HTML hidden input field containing the spoofed value.

Processes to implement method spoofing

We can do method spoofing in Laravel by following methods.

Using @method Blade directive:

We can create hidden input field for method spoofing using @method function. This will create a hidden field with name _method.

<form method="POST" action="<?php echo route('SOME_ROUTE');?>"> 
@method('PUT')
@csrf 
</form>
Using method_field function:

We can create hidden input field for method spoofing using method_field function. This will also create a hidden field with name _method.

<form method="POST" action="<?php echo route('SOME_ROUTE');?>">
{{ method_field('DELETE') }}
</form>
Using raw HTML input hidden field

In the above two processes, we have used Laravel’s blade directive and Laravel’s helper function, but by directly adding a hidden input field to an HTML form, we can also perform method spoofing.

<form method="POST" action="<?php echo route('SOME_ROUTE');?>">
    <input type="hidden" name="_method" value="PUT">
    <input type="hidden" name="_token" value="{{ csrf_token() }}">
</form>

I hope the above discussion has helped you understand Laravel method spoofing. You can know more details about Laravel route including form method spoofing at: https://laravel.com/docs/10.x/routing.