Using the @method override form is called form method spoofing in Laravel. HTML forms don’t support actions like PATCH, PUT
, or DELETE
. So, when we need to define routes with PATCH
, PUT
, or DELETE
that we call from an HTML form, we will need to add a hidden _method
field in the form. The value sent with the _method
field will be used as the HTTP request method.
Blade directives like @method are shortcut codes that help implement and get basic PHP structure control, like loops and conditional statements. They make your code snippets clean and easier to understand.
However, these directives can only be used in the blade templates, not in your controllers. Some other blade directives supported by the Laravel blade are @foreach
, @forelse
, @lang
, @include
, and @can.
<form action="/example" method="POST">
<input type="hidden" name="_method" value="PUT">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
</form>
However, a more convenient way is to use the @method blade directive that will generate the _method input field. Therefore, @method
blade directive helps create the field for you:
<form action='some-url' method='POST'>
@csrf
@method('PATCH')
...
</form>
However before using it in the form action in a blade file, you should create a service provider add the @method directive in a BladeServiceProvider file under app\Providers directory.
php artisan make:provider BladeServiceProvider
Here, in the boot() method, your Blade directive should be defined as shown below.
public function boot()
{
Blade::directive('csrf', function ()
{
return '<?php echo csrf_field(); ?>';
});
Blade::directive('method', function ($method)
{
return '<input type="hidden" name="_method" value="<?php echo strtoupper(' . $method . '); ?>">';
});
}
You may then add the newly created provider in the config/app.php
file to the providers array as shown below.
'providers' => [
...
App\Providers\BladeServiceProvider::class,
...
You can now use the @method override and @crsf in the form of a blade file.