Forms & CSRF
Submit data the Laravel way — with built-in security.
What you will learn
- Build a form that posts to a route
- Use the CSRF token
- Read input in the controller
A Blade form
Forms post to a route. Laravel requires a @csrf token (security against forged requests) — just add the directive.
<form action="/products" method="POST">
@csrf
<input type="text" name="name">
<input type="number" name="price">
<button type="submit">Add</button>
</form>Reading the form: action="/products" is the URL the data is sent to, and method="POST" means we are sending (creating) data, not just viewing. @csrf drops in a hidden security token (more on that below). Each <input> has a name — name and price — and those names are exactly how the controller will look the values up. The submit button sends everything.
When the form is submitted, the matching route runs this controller method, which reads the values out of the request:
// in the controller
public function store(Request $request)
{
$name = $request->input('name');
$price = $request->input('price');
// ... save it ...
return redirect('/products');
}The $request object holds everything the user submitted. $request->input('name') pulls out the value of the input whose name="name", and likewise for price. After saving, return redirect('/products') sends the browser to the products list — the standard "save, then redirect" pattern that stops a refresh from submitting the form twice.
Here is the whole journey of a Laravel form, start to finish:
- The user fills in the Blade form and clicks submit.
- The browser sends a POST request to the form’s
actionURL (/products), including the hidden@csrftoken. - Laravel checks the CSRF token to confirm the request really came from your site.
- The matching route sends the request to the controller’s
storemethod. - Inside
store,$request->input('name')reads each submitted field by itsname. - The controller saves the data, then
redirect()sends the user to another page.
Watch out: Every POST form in Laravel needs @csrf — it adds a hidden token that proves the request came from your site. Without it, Laravel rejects the submission (a security feature).
Q. What does @csrf add to a Laravel form?
✍️ Practice
- Build a Blade form with
@csrfthat posts to a route. - Read the values in the controller with
$request->input().
🏠 Homework
- Build an “add post” form wired to a controller method.