In modern web applications, handling and validating incoming data is crucial. Laravel provides powerful request validation, but what if you need to cast input data into specific types automatically? Meet Cambia, a PHP package designed to streamline type casting for request input in Laravel applications.
What is Cambia?
Cambia is a PHP package that enhances Laravel’s request handling by allowing developers to cast input data to various types effortlessly. This package simplifies working with input data by automatically converting it into desired types, making your code cleaner and more efficient.
Key Features
- Flexible Casting: Cambia supports a wide range of data types, including integers, floats, booleans, strings, arrays, JSON, dates, and more. You can even define custom casting logic for complex scenarios.
- Seamless Integration: Cambia integrates seamlessly with Laravel’s existing request validation. By adding a trait and a casts method to your request class, you can start casting input data with minimal setup.
- Custom Casts: For advanced use cases, Cambia allows you to create custom cast classes, enabling complex transformations and logic beyond the built-in types.
Getting Started
To use Cambia in your Laravel project, first install it via Composer:
composer require nickescobedo/cambia
Next, add the NickEscobedo\Cambia\CastRequestAttributes
trait to your request class and define the casts method to specify the types you want to cast:
use NickEscobedo\Cambia\CastRequestAttributes;
class MyRequest extends FormRequest
{
use CastRequestAttributes;
public function rules(): array
{
return [
'isActive' => 'required|string',
];
}
public function casts(): array
{
return [
'isActive' => 'boolean',
];
}
}
With this setup, you can access the casted input using the castedInput method:
$active = $request->castedInput('isActive'); // returns a boolean
Available Casts
Cambia supports a variety of built-in casts, including:
- Primitive types: int, float, boolean, string, array
- Complex types: JSON, collection, date, datetime, timestamp
- Custom casts: Implement your casting logic by creating classes that implement
CastsRequestAttributes
.
Conclusion
Cambia is a powerful tool for Laravel developers looking to enhance their request handling with type casting. By simplifying data transformation, Cambia helps you write cleaner and more maintainable code. Try Cambia today and see how it can streamline your Laravel projects!
For more details and examples, check out the Cambia GitHub repository. Your feedback and contributions are welcome!