File: D:/HostingSpaces/bomacon/bomacon.nl/app/Forms/FormService.php
<?php
/**
* Created by PhpStorm.
* User: mike
* Date: 28/09/17
* Time: 15:58
*/
namespace App\Forms;
use App\Http\Requests\Request;
use Carbon\Carbon;
use Illuminate\Foundation\Http\FormRequest;
final class FormService
{
/**
* Origin from where the request was done
* f.e. 'contact','offer'
*
* @var
*/
protected $origin;
/**
* Set the origin of the form request
*
* @param $origin
*/
public function setOrigin($origin)
{
$this->origin = $origin;
}
/**
* Store the request in the database
*
* @param FormRequest $request
*/
public function storeRequest(FormRequest $request)
{
$storeRequest = $request->duplicate();
$storeRequest = $storeRequest->except('_token', '_willie');
foreach ($storeRequest as $name => $value) {
if (! \Schema::hasColumn('requests', $name)) {
\Schema::table('requests', function ($table) use ($name) {
$table->text($name)->nullable();
});
}
}
$dbRequest = new \App\Forms\Models\Request();
$dbRequest->origin = $this->origin;
$dbRequest->created_at = Carbon::now()->toDateTimeString();
$dbRequest->updated_at = Carbon::now()->toDateTimeString();
foreach ($storeRequest as $name => $value) {
// Convert non-scalar values (arrays, objects like UploadedFile) to a storable representation
if (is_array($value)) {
// If this is an array of uploaded files, store each and save JSON of paths
$allAreFiles = !empty($value) && collect($value)->every(function ($v) { return $v instanceof \Illuminate\Http\UploadedFile; });
if ($allAreFiles) {
$paths = [];
foreach ($value as $file) {
$paths[] = $file->store('contact-uploads');
}
$dbRequest->$name = json_encode($paths);
} else {
// For other arrays, store as JSON string
$dbRequest->$name = json_encode($value);
}
} elseif ($value instanceof \Illuminate\Http\UploadedFile) {
// Store single uploaded file to storage and keep the stored path
$path = $value->store('contact-uploads');
$dbRequest->$name = $path;
} elseif (is_object($value)) {
// Fallback for other objects: JSON-encode public properties
$dbRequest->$name = json_encode($value);
} else {
$dbRequest->$name = $value;
}
}
$dbRequest->save();
}
}