Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to get the contents of the HTTP Request body in Laravel?
In Laravel, you can retrieve HTTP request body contents using the Illuminate\Http\Request class. This class provides several methods to access input data, cookies, and files from HTTP requests in different formats.
Using $request->all() Method
The all() method retrieves all input data from the request and returns it as an array
<?php
public function validateform(Request $request) {
$input = $request->all();
print_r($input);
}
?>
Output
Array ( [_token] => 367OQ9dozmWlnhu6sSs9IvHN7XWa6YKpSnnWrBXx [name] => Rasika Desai [email] => rasika@gmail.com [age] => 20 [address] => Pune )
Using $request->collect() Method
The collect()
<?php
public function validateform(Request $request) {
$input = $request->collect();
print_r($input);
}
?>
Output
Illuminate\Support\Collection Object (
[items:protected] => Array(
[_token] => 367OQ9dozmWlnhu6sSs9IvHN7XWa6YKpSnnWrBXx
[name] => Rasika Desai
[email] => rasika@gmail.com
[age] => 20
[address] => Pune
)
[escapeWhenCastingToString:protected] =>
)
Using $request->getContent() Method
The getContent() method returns the raw HTTP request body as a URLencoded string
<?php
public function validateform(Request $request) {
$input = $request->getContent();
echo $input;
}
?>
Output
_token=367OQ9dozmWlnhu6sSs9IvHN7XWa6YKpSnnWrBXx&name=Rasika+Desai&email=rasika%40gmail.com&age=20&address=Pune
Using php://input Stream
You can also access the raw request body directly using PHP's input stream
<?php
$data = file_get_contents('php://input');
print_r($data);
?>
Output
_token=367OQ9dozmWlnhu6sSs9IvHN7XWa6YKpSnnWrBXx&name=Rasika+Desai&email=rasika%40gmail.com&age=20&address=Pune
Comparison
| Method | Return Type | Best Use Case |
|---|---|---|
all() |
Array | General form processing |
collect() |
Collection | When you need Collection methods |
getContent() |
String | Raw request body access |
php://input |
String | Direct stream access |
Conclusion
Laravel provides multiple ways to access HTTP request body contents. Use all() for standard form processing, collect() for Collection features, and getContent() or php://input for raw body access.
Advertisements
