Creating multiple records at once in Laravel Nova is not supported out of the box, but you can achieve this by creating a custom tool or action. Here's a general approach to creating a custom action that allows you to paste in a JSON array and create related records in bulk:
- Create a new Nova action.
- Add a textarea field to the action where you can paste your JSON.
- Parse the JSON in the action's
handlemethod and create the records.
Here's a step-by-step example:
- Generate a new Nova action using the Artisan command:
php artisan nova:action ImportJson
- Edit the generated action class to add a textarea for the JSON input:
// app/Nova/Actions/ImportJson.php
use Laravel\Nova\Actions\Action;
use Laravel\Nova\Fields\ActionFields;
use Laravel\Nova\Fields\Textarea;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
class ImportJson extends Action
{
public $name = 'Import JSON';
public function fields()
{
return [
Textarea::make('JSON Data')
->rules('required', 'json')
->help('Paste your JSON array here.'),
];
}
public function handle(ActionFields $fields, Collection $models)
{
// Begin a transaction in case one of the inserts fails
DB::beginTransaction();
try {
$data = json_decode($fields->get('JSON Data'), true);
foreach ($data as $itemData) {
// Assuming you have a model called Item and related models
$item = Item::create($itemData['item']);
foreach ($itemData['related'] as $relatedData) {
// Create related records, for example, a one-to-many relationship
$item->relatedModels()->create($relatedData);
}
}
DB::commit();
return Action::message('Items and related records have been created successfully!');
} catch (\Exception $e) {
DB::rollBack();
return Action::danger('An error occurred: ' . $e->getMessage());
}
}
public function actionDescription()
{
return 'This action will import items and their related records from a JSON array.';
}
}
- Register the action with the relevant resource in Nova.
// app/Nova/YourResource.php
public function actions(Request $request)
{
return [
new Actions\ImportJson,
];
}
- Now, when you view your resource in Nova, you should see the "Import JSON" action in the actions dropdown. You can paste your JSON array into the textarea and execute the action to create the records.
Remember to adjust the handle method to fit your specific models and relationships. Also, ensure that your JSON structure matches the expected format for your models and their relationships.
This is a basic example and does not include validation or error handling for the JSON structure. You may want to add additional checks to ensure the JSON is formatted correctly and contains all the necessary data before attempting to create the records.