Cast request input in Laravel.
composer require nickescobedo/cambia
- Add
NickEscobedo\Cambia\CastRequestAttributes
trait to your request class. - Add a
casts
function to your request class that returns an array. - Access casts via request attributes
$request->castedInput('inputKey')
. Note: The request key must have be validated in rules before it will attempt to cast.
class Cast extends FormRequest
{
use CastRequestAttributes;
public function rules(): array
{
return [
'toBoolean' => 'string', // Fields not present in validation will not cast
];
}
public function casts(): array
{
return [
'toBoolean' => 'boolean',
];
}
}
$request->castedInput('toBoolean')
will return a boolean value.
- int
- integer
- float
- double
- decimal:int
- string
- boolean
- object
- array
- json
- collection
- date
- datetime or datetime:format
- immutable_date
- immutable_datetime or immutable_datetime:format
- timestamp
Custom casts allow for more complex casting logic. Enums and custom classes can be used. Custom cast classes must implement NickEscobedo\Cambia\CastsRequestAttributes
.
enum Status: string
{
case Pending = 'pending';
}
public function casts(): array
{
return [
'status' => Status::class,
];
}
The class must implement NickEscobedo\Cambia\CastsRequestAttributes
.
use Illuminate\Http\Request;
use NickEscobedo\Cambia\CastsRequestAttributes;
class JsonCast implements CastsRequestAttributes
{
public function get(Request $request, string $key, mixed $value, array $attributes)
{
return json_decode($value, true);
}
}
class Cast extends FormRequest
{
use CastRequestAttributes;
public function rules(): array
{
return [
'toBoolean' => 'string', // Fields not present in validation will not cast
];
}
public function casts(): array
{
return [
'toBoolean' => JsonCast::class,
];
}
}