Skip to content

Commit

Permalink
Form submission export request as seprate class with validation
Browse files Browse the repository at this point in the history
  • Loading branch information
chiragchhatrala committed Jan 6, 2025
1 parent 3505100 commit 4654125
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 8 deletions.
11 changes: 3 additions & 8 deletions api/app/Http/Controllers/Forms/FormSubmissionController.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use App\Exports\FormSubmissionExport;
use App\Http\Controllers\Controller;
use App\Http\Requests\AnswerFormRequest;
use App\Http\Requests\FormSubmissionExportRequest;
use App\Http\Resources\FormSubmissionResource;
use App\Jobs\Form\StoreFormSubmissionJob;
use App\Models\Forms\Form;
Expand All @@ -14,7 +15,6 @@
use Illuminate\Support\Str;
use Maatwebsite\Excel\Facades\Excel;
use Vinkla\Hashids\Facades\Hashids;
use Illuminate\Http\Request;

class FormSubmissionController extends Controller
{
Expand Down Expand Up @@ -47,14 +47,9 @@ public function update(AnswerFormRequest $request, $id, $submissionId)
]);
}

public function export(Request $request, string $id)
public function export(FormSubmissionExportRequest $request, string $id)
{
$request->validate([
'columns' => 'required|array',
'columns.*' => 'boolean'
]);

$form = Form::findOrFail((int) $id);
$form = $request->form;
$this->authorize('view', $form);

$allRows = [];
Expand Down
38 changes: 38 additions & 0 deletions api/app/Http/Requests/FormSubmissionExportRequest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<?php

namespace App\Http\Requests;

use App\Models\Forms\Form;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Request;

class FormSubmissionExportRequest extends FormRequest
{
public Form $form;

public function __construct(Request $request)
{
$this->form = Form::findOrFail($request->route('id'));
}

public function rules()
{
$validColumns = collect(array_merge(
$this->form->properties,
$this->form->removed_properties ?? []
))->pluck('id')->toArray();
$validColumns[] = 'created_at';

return [
'columns' => 'required|array',
'columns.*' => ['boolean', 'required'],
'columns' => [function ($attribute, $value, $fail) use ($validColumns) {
$submittedColumns = array_keys($value);
$invalidColumns = array_diff($submittedColumns, $validColumns);
if (!empty($invalidColumns)) {
$fail('The columns contain invalid values: ' . implode(', ', $invalidColumns));
}
}],
];
}
}

0 comments on commit 4654125

Please sign in to comment.