Overview
The RequestBody helper extracts and manipulates parameters from a Laravel Request body. It supports JSON, form-data, multipart, raw body content, and works with any HTTP method (GET, POST, PUT, PATCH, DELETE, etc.). It excludes query parameters and route parameters by default.
Class Reference
use Ronu\RestGenericClass\Core\Helpers\ RequestBody ;
Methods
get()
Extract parameters from request body without query params or route params.
public static function get (
Request $request ,
string | array | null $keys = null ,
array $options = []
) : mixed
The Laravel Request instance
keys
string|array|null
default: "null"
null: Return all body parameters
string: Return single parameter (supports dot notation)
array: Return multiple parameters
Configuration options: Default value when key not found
Only include specified keys
Trim whitespace from string values
Convert empty strings to null
Remove Laravel internal fields (_token, _method)
Type casting rules (e.g., [‘age’ => ‘int’, ‘active’ => ‘bool’])
Throw exception if required keys are missing
Returns array when keys is null or array
Returns mixed when keys is a string
Example Usage
use Ronu\RestGenericClass\Core\Helpers\ RequestBody ;
// Get all body parameters
$body = RequestBody :: get ( $request );
// ['name' => 'John', 'email' => '[email protected] ']
// Get single parameter
$email = RequestBody :: get ( $request , 'email' );
// '[email protected] '
// Get nested parameter with dot notation
$city = RequestBody :: get ( $request , 'user.address.city' );
// 'New York'
// Get multiple parameters
$data = RequestBody :: get ( $request , [ 'name' , 'email' ]);
// ['name' => 'John', 'email' => '[email protected] ']
// With default value
$phone = RequestBody :: get ( $request , 'phone' , [ 'default' => 'N/A' ]);
// 'N/A' (if phone not in body)
// With type casting
$age = RequestBody :: get ( $request , 'age' , [ 'casts' => [ 'age' => 'int' ]]);
// 25 (as integer)
all()
Explicit alias to get all parameters from request body.
public static function all ( Request $request , array $options = []) : array
The Laravel Request instance
Configuration options (same as get() method)
All body parameters as an associative array
Example Usage
$body = RequestBody :: all ( $request );
// ['name' => 'John', 'email' => '[email protected] ', 'age' => '25']
// With trimming and empty to null
$body = RequestBody :: all ( $request , [
'trim_strings' => true ,
'empty_to_null' => true ,
]);
only()
Get a single parameter with default value.
public static function only (
Request $request ,
string $key ,
mixed $default = null ,
array $options = []
) : mixed
The Laravel Request instance
The parameter key (supports dot notation)
Default value if key not found
Additional configuration options
The parameter value or default
Example Usage
pick()
Get multiple specific parameters.
public static function pick (
Request $request ,
array $keys ,
array $options = []
) : array
The Laravel Request instance
Array of keys to extract (supports dot notation)
Associative array with only specified keys
Example Usage
$data = RequestBody :: pick ( $request , [ 'name' , 'email' , 'phone' ]);
// ['name' => 'John', 'email' => '[email protected] ', 'phone' => '555-1234']
// With nested keys
$data = RequestBody :: pick ( $request , [
'user.name' ,
'user.email' ,
'settings.theme'
]);
require()
Validate that required keys exist and return them (throws exception if missing).
public static function require (
Request $request ,
array $requiredKeys ,
array $options = []
) : array
The Laravel Request instance
Array of required keys (supports dot notation)
Associative array with required keys
throws
\InvalidArgumentException
Thrown when one or more required keys are missing
Example Usage
try {
$data = RequestBody :: require ( $request , [ 'name' , 'email' , 'password' ]);
// ['name' => 'John', 'email' => '[email protected] ', 'password' => 'secret']
User :: create ( $data );
} catch ( \ InvalidArgumentException $e ) {
// Exception message: "Missing required body parameters: password"
return response () -> json ([ 'error' => $e -> getMessage ()], 422 );
}
Type Casting
The casts option supports automatic type conversion:
Supported Cast Types
Parse JSON string to array
Convert to Carbon date instance
Convert to Carbon using specific format (e.g., date:Y-m-d)
Custom transformation function
Type Casting Examples
$data = RequestBody :: get ( $request , null , [
'casts' => [
'age' => 'int' ,
'price' => 'float' ,
'active' => 'bool' ,
'tags' => 'array' ,
'metadata' => 'json' ,
'birth_date' => 'date:Y-m-d' ,
'created_at' => 'date' ,
'name' => fn ( $v ) => strtoupper ( $v ), // Custom cast
]
]);
// Input body:
// {
// "age": "25",
// "price": "19.99",
// "active": "true",
// "tags": "tag1,tag2",
// "metadata": "{\"key\":\"value\"}",
// "birth_date": "1998-05-15",
// "created_at": "2024-01-15 10:30:00",
// "name": "john"
// }
// Result:
// [
// 'age' => 25, // int
// 'price' => 19.99, // float
// 'active' => true, // bool
// 'tags' => ['tag1', 'tag2'], // array
// 'metadata' => ['key' => 'value'], // decoded JSON
// 'birth_date' => Carbon instance, // Carbon date
// 'created_at' => Carbon instance, // Carbon date
// 'name' => 'JOHN' // custom cast
// ]
Filtering Options
Only Specific Keys
$body = RequestBody :: get ( $request , null , [
'only' => [ 'name' , 'email' , 'phone' ]
]);
// Only includes name, email, and phone (ignores all others)
Exclude Keys
$body = RequestBody :: get ( $request , null , [
'except' => [ 'password' , 'secret_key' ]
]);
// Includes everything except password and secret_key
Drop Internal Fields
// By default, _token and _method are removed
$body = RequestBody :: get ( $request );
// To keep internal fields:
$body = RequestBody :: get ( $request , null , [
'drop_internal' => false
]);
String Normalization
Trim Strings
$body = RequestBody :: get ( $request , null , [
'trim_strings' => true // Default
]);
// ' John ' becomes 'John'
Empty to Null
$body = RequestBody :: get ( $request , null , [
'empty_to_null' => true
]);
// '' (empty string) becomes null
Supported Content Types
JSON (application/json)
// POST /api/users
// Content-Type: application/json
// {"name": "John", "email": "[email protected] "}
$body = RequestBody :: get ( $request );
// ['name' => 'John', 'email' => '[email protected] ']
// POST /api/users
// Content-Type: application/x-www-form-urlencoded
// name=John&[email protected]
$body = RequestBody :: get ( $request );
// ['name' => 'John', 'email' => '[email protected] ']
// POST /api/users
// Content-Type: multipart/form-data
$body = RequestBody :: get ( $request );
// Excludes uploaded files by default
Raw Content
// Works with raw request body content
// Automatically detects JSON, URL-encoded, or key=value formats
Complete Example
use Ronu\RestGenericClass\Core\Helpers\ RequestBody ;
class UserController extends Controller
{
public function store ( Request $request )
{
// Extract required fields with type casting
try {
$data = RequestBody :: require ( $request , [ 'name' , 'email' , 'age' ], [
'casts' => [
'age' => 'int' ,
'active' => 'bool' ,
],
'trim_strings' => true ,
'empty_to_null' => true ,
]);
// Create user with validated data
$user = User :: create ( $data );
return response () -> json ( $user , 201 );
} catch ( \ InvalidArgumentException $e ) {
return response () -> json ([
'error' => 'Validation failed' ,
'message' => $e -> getMessage (),
], 422 );
}
}
public function update ( Request $request , $id )
{
// Get only specific fields
$data = RequestBody :: pick ( $request , [ 'name' , 'email' , 'bio' ], [
'trim_strings' => true ,
'except' => [ 'id' , 'created_at' , 'updated_at' ],
]);
$user = User :: findOrFail ( $id );
$user -> update ( $data );
return response () -> json ( $user );
}
}