Created
March 19, 2021 17:47
-
-
Save waska14/f3be9c1cf0731a85753c9f34e9fca348 to your computer and use it in GitHub Desktop.
Laravel: how to merge new UploadedFile object in Request / FormRequest?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Http\Requests\Files; | |
use App\Helpers\File\FileHelper; | |
use App\Overrides\FormRequest\FormRequest; | |
class UploadFileRequest extends FormRequest | |
{ | |
public function rules(): array | |
{ | |
return [ | |
'file' => 'required|file', | |
]; | |
} | |
/** | |
* This method prepares file instante | |
*/ | |
protected function prepareForValidation() | |
{ | |
// This condition means that file parameter is received, but it is not file. | |
// Potentially it is base64 encoded file. | |
// Let's get new UploadedFile object from it and then merge it in the request | |
if (!$this->file('file') && $this->input('file')) { | |
// Create new UploadedFile object from base64 string | |
// See the helper here: https://gist.github.com/waska14/8b3bcebfad1f86f7fcd3b82927576e38 | |
$file = FileHelper::fromBase64($this->input('file')); | |
// Add it in files | |
$this->files->add(['file' => $file]); | |
// Merge it in request also (As I found this is not needed in every case) | |
$this->merge(['file' => $file]); | |
// Clear convertedFiles array (set null). | |
// This action forces $request->file() method to convert request files again | |
// So when you use $request->file('file') or $request->allFiles() or something like this, our new 'file' | |
// object will be available! | |
$this->convertedFiles = null; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment