Skip to content

Instantly share code, notes, and snippets.

@AlexandreGerault
Last active May 16, 2020 12:59
Show Gist options
  • Save AlexandreGerault/2899923858335d32c1c375e9f8c15a0d to your computer and use it in GitHub Desktop.
Save AlexandreGerault/2899923858335d32c1c375e9f8c15a0d to your computer and use it in GitHub Desktop.
<?php
class CreateCompanyDiagnosticRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
$rules = ['needs' => 'required|array'];
$comments = array_filter($this->request->all(), fn($elt) => preg_match('#^comment-[0-9]+$#', $elt), ARRAY_FILTER_USE_KEY);
foreach ($comments as $key => $value)
{
$rules[$key] = 'nullable|string';
}
return $rules;
}
}
<?php
class DiagnosticsController extends Controller
{
/**
* Store a newly created resource in storage.
*
* @param CreateCompanyDiagnosticRequest $request
* @return RedirectResponse|Redirector
*/
public function store(CreateCompanyDiagnosticRequest $request)
{
$validated = $request->validated();
$needs_validated = $validated['needs'];
$comments_validated = array_filter($validated, fn($key) => (preg_match('#^comment-[0-9]+$#', $key) && $validated[$key]), ARRAY_FILTER_USE_KEY);
if (auth()->guest()) {
$request->session()->put('pending_company_diagnostic', [
'user_id' => null,
'needs' => $needs_validated,
'comments' => $comments_validated
]);
return redirect(route('login'));
} else {
$diagnostic = Diagnostic::create([
'user_id' => auth()->user()->id,
'uuid' => uniqid()
]);
$diagnostic->addNeeds($needs_validated);
foreach ($comments_validated as $key => $content) {
preg_match('#([0-9]+)$#', $key, $matches);
$categroryId = $matches[0];
$comment = new Comment;
$comment->content = $content;
$comment->diagnostic()->associate($diagnostic);
$comment->category()->associate($categroryId);
$comment->save();
}
return redirect($diagnostic->path());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment