0
0
LaravelHow-ToBeginner · 3 min read

How to Use Route::post in Laravel for Handling POST Requests

In Laravel, use Route::post to define a route that handles HTTP POST requests. It takes a URL path and a callback or controller action to process the request data sent by forms or APIs.
📐

Syntax

The Route::post method defines a route that listens for HTTP POST requests on a specified URL path. It requires two main parts:

  • URL path: The endpoint where the POST request is sent.
  • Action: A closure (anonymous function) or a controller method that handles the request.

This route only responds to POST requests, commonly used for submitting form data or API calls.

php
Route::post('/submit', function () {
    // Handle POST request logic here
    return 'Form submitted!';
});
💻

Example

This example shows how to create a POST route that accepts form data and returns a confirmation message. It uses a closure to handle the request.

php
<?php

use Illuminate\Support\Facades\Route;
use Illuminate\Http\Request;

Route::post('/submit', function (Request $request) {
    $name = $request->input('name');
    return "Hello, $name! Your form was submitted.";
});
Output
If you send a POST request to /submit with form data name=John, the response will be: Hello, John! Your form was submitted.
⚠️

Common Pitfalls

Common mistakes when using Route::post include:

  • Defining the route with Route::get instead of Route::post, causing POST requests to fail.
  • Not including CSRF tokens in forms, which Laravel requires for POST requests by default.
  • Forgetting to import the Request class when using it in closures or controllers.

Always ensure your form uses method="POST" and includes @csrf in Blade templates.

php
/* Wrong: Using get instead of post */
Route::get('/submit', function () {
    return 'This will not handle POST requests';
});

/* Right: Use post for POST requests */
Route::post('/submit', function () {
    return 'This handles POST requests correctly';
});
📊

Quick Reference

TermDescription
Route::post('/url', action)Defines a route for HTTP POST requests to '/url'
ClosureAn anonymous function that handles the request inline
Controller@methodA controller method that processes the POST request
Request $requestInjects the HTTP request data into the handler
@csrfBlade directive to include CSRF token in forms for security

Key Takeaways

Use Route::post to define routes that respond only to HTTP POST requests.
Always include CSRF tokens in your forms to avoid Laravel security errors.
You can handle POST requests with closures or controller methods.
Import the Request class to access form or API data sent via POST.
Ensure your HTML forms use method="POST" to match the route definition.