Using Form Method Spoofing and CSRF Protection in Laravel
This article explains how to create Laravel routes for GET and POST forms, handle CSRF protection, disable it when necessary, configure CSRF whitelist, and use form method spoofing to send PUT requests via HTML forms.
We start by noting that the most popular API design style is RESTful, which defines five common HTTP methods: GET, POST, PUT, PATCH, and DELETE. While HTML forms natively support only GET and POST, Laravel allows the other methods through form spoofing.
Preparation
First, create two routes: one that returns a form view and another that receives the form submission.
Route::get('form', function () {
return view('form');
});
Route::any('getform', function () {
return \Illuminate\Support\Facades\Request::method();
});Next, build a simple GET request form:
<form method="get" action="/getform">
<input type="submit" value="sub" />
</form>Submitting this form displays GET , confirming the request succeeded.
CSRF Protection
When switching the form method to POST, Laravel returns a 419 "page expired" error because of its default CSRF protection. To allow POST (and other non‑GET methods), include a CSRF token in the form:
<input type="hidden" name="_token" value="{{csrf_token()}}">Laravel also provides a shortcut directive:
@csrfDisabling CSRF Protection
Although generally discouraged, you can disable CSRF for the whole application by commenting out the line in app/Http/Middleware/VerifyCsrfToken.php that registers the middleware class.
CSRF Whitelist
For specific URLs (e.g., third‑party API endpoints) you can add them to the $except array in VerifyCsrfToken.php :
class VerifyCsrfToken extends Middleware {
protected $except = [
/* whitelist */
'http://example.com/api/*',
'api/*',
'a/b/*',
];
}Form Method Spoofing
After understanding CSRF, you can spoof other HTTP methods by adding a hidden _method field or using the Blade directive:
<input type="hidden" name="_method" value="PUT"> @method('PUT')Here is a complete form that spoofs a PUT request:
<form method="post" action="/getform">
@csrf
@method('PUT')
<input type="submit" value="sub" />
</form>For further details and the original article, follow the provided link.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.