I’m pretty new to laravel and I’m trying to find a better way to store a json list/array in mysql using the api. This is my current implementation of how I am able to get everything to work but I have to wonder if my lack of experience is blinding me from a cleaner solution and this would be a good way to learn.
Any thoughts?
Json sent from postman
[
{"ItemNum":"01","ItemName":"Well Bourbon"},
{"ItemNum":"016600000760","ItemName":"Rose's Grenadine 1L"},
{"ItemNum":"02","ItemName":"Beam Apple"},
{"ItemNum":"02835727","ItemName":"Cigs"},
{"ItemNum":"029929115411","ItemName":"Licor 43 750mil"}
]
StoreInventoryRequest.php
<?php
namespace AppHttpRequests;
use IlluminateContractsValidationValidationRule;
use IlluminateFoundationHttpFormRequest;
class StoreInventoryRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*/
public function authorize(): bool
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
return [
'*.ItemNum' => 'required|string',
'*.ItemName' => 'required|string',
];
}
}
InventoryController.php
public function store(StoreInventoryRequest $request)
{
foreach ($request->validated() as $item)
{
$inventory = Inventory::create($item);
InventoryResource::make($inventory);
}
}
Initally I used this to get a single json object to save but it does not work for a json list/array
public function store(StoreInventoryRequest $request)
{
$inventory = Inventory::create($request->validated());
return InventoryResource::make($inventory);
}