I send to Laravel this JSON data:
[
{"name":"...", "description": "..."},
{"name":"...", "description": "..."}
]
I have a StoreRequest class extends FormRequest:
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class StoreRequest extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'name' => 'required|string|min:1|max:255',
'description' => 'nullable|string|max:65535'
];
}
}
In my controller I have this code, but it doesn't work with array:
public function import(StoreRequest $request) {
$item = MyModel::create($request);
return Response::HTTP_OK;
}
I found this solution to handle arrays in the Request rules():
public function rules()
{
return [
'name' => 'required|string|min:1|max:255',
'name.*' => 'required|string|min:1|max:255',
'description' => 'nullable|string|max:65535'
'description.*' => 'nullable|string|max:65535'
];
}
How can I update the StoreRequest and/or the import() code to avoide duplicate lines in rules()?
[]and was confused. Please have a look at the linked question and my answer there.$validator = Validator::make()what I don't use, because I have a StoreRequest class. Or if this is a same thing, then I dont understand how can I use this two together.rules()method are used to create aValidatoras discussed in the other question. It is the same thing, just an abstraction of it...StoreRequest) are used to extract logic from the controller. You can do exactly the same stuff also with a normalRequestobject and theValidatorin your controller. It is still recommended to use form requests in order to keep your controller small and simple.