Laravel RequestCaster
, (*1)
Requirements: I've only tested this package with Laravel 5.5, please help me by testing this package in older versions of Laravel, (*2)
Installation
Install this package by typing the following command:, (*3)
composer require stahiralijan/request-caster
Usage
Let's learn from an example:, (*4)
You want to be able to save the submitted data but you don't want to make a mess in the controller method like this:, (*5)
public function store(UserFormRequest $request)
{
...
$first_name = ucfirst($request->first_name); // or ucfirst($request->get('first_name')
$last_name = ucfirst($request->last_name); // or ucfirst($request->get('last_name')
...
$user = User::create([
...
'first_name' => $first_name,
'last_name' => $last_name,
...
]);
...
// after handling model stuff
return redirect(route('users.index'))
->with('message'=>"User ({$user->first_name} {$user->last_name}) created!");
}
As you can see after a while you start to wondering what if there is a way you could automate this process so that
your controller would look elegant and clean. With this package you can just do that:, (*6)
Step 1:
Use the RequestCaster
Trait in your form request (in this case UserFormRequest
):, (*7)
...
use Stahiralijan\RequestCaster\Traits\RequestCasterTrait;
...
class UserFormRequest extends FormRequest
{
use RequestCasterTrait;
...
}
Step 2:
Define the Request attributes that are required to be casted:, (*8)
class UserFormRequest extends FormRequest
{
use RequestCasterTrait;
protected $toUCFirstWords = ['first_name','last_name'];
// More about this is explained below
protected $joinStrings = ['fullname'=>' |first_name,last_name'];
...
}
Finally
...and that's all you needed to do, first_name
and last_name
are automatically capitalized. Also, you don't need to worry about your form data being getting dirty before validation because these castings will run after the validator validates the form data., (*9)
public function store(UserFormRequest $request)
{
// first_name and last_name
$user = User::create($request->all());
...
// after handling model stuff
return redirect(route('users.index'))
->with('message'=>"User ({$request->full_name}) created!");
}
The following casts are available:
- $toLowerCaseWords
: Applies strtolower()
to the selected field(s).
- $toUpperCaseWords
: Applies strtoupper()
to the selected field(s).
- $toUCFirstWords
: Applies ucwords()
to the selected field(s).
- $toSlugs
: Applies str_slug()
to the selected field(s).
- $toIntegers
: Casts selected field(s) to int
.
- $toFloats
: Casts selected field(s) to float
.
- $toBooleans
: Casts selected field(s) to bool
.
- $toArrayFromJson
: Applies json_decode()
to the selected fields.
- $joinStrings
: Joins two or more fields and sets the result in new field specified in the array key, syntax: $joinStrings = ['newField' => 'glue|field1,field2,...,fieldn']
, (*10)
Available methods
-
collection(array $keys)
returns an object of Illuminate\Support\Collection
-
dd()
dumps and dies all the fields submitted in request
-
dump()
dumps all the fields submitted in request
You can use this method to get a collection (Illuminate\Support\Collection
) of all the attributes, (*11)
public function store(UserFormReques $request)
{
$request->collection()->filter(function($item){
...
});
// or
$request->collection()->map(function($item){
...
});
}
How to cast
All of the properties are pretty straight forward, you define the attributes that needs to be casted like this:, (*12)
// Convert the defined attributes to Upper-case
$toUpperCaseWords = ['product_code'];
// Upper-case the first letter of the words defined below
$toUCFirstWords = ['display_name'];
// Convert the following attributes into slugs
$toSlugs = ['product_name'];
You got the idea about the usage of the simple stuff, now one special transformation / caster, (*13)
$joinStrings = ['fullname'=>' |first_name,last_name'];
- Here
fullname
will be a new attribute of the FormRequest
which does not exists in the either the form or the FormRequest in the current context.
- Notice a space
' '
in the starting of value is the glue of the two attributes
- Next
|
is the separator between the glue and the desired attributes
- Next you add the attributes that needs to be glued.
If first_name
is Tahir
and last_name
is Jan
the output will be Tahir Jan
according to the above rule, and can be accessed with $request->fullname
or $request->get('fullname')
, (*14)