[Vuejs]-Store nested data with files with vuejs & laravel

0👍

Base64 is not in the request file, you have to read the string and convert it back to the image $request->get('foreignCitizen.passports[0].scans[0]'). An other option is to store the person and latter on submit the passport files with FormData so POST /person/1/scans will attach the documents to person 1.

With this validator you can validate the images.

    Validator::extend('image64',function($attribute, $base64Data, $mimeTypes, $validator) {
        // strip out data uri scheme information (see RFC 2397)
        if (strpos($base64Data, ';base64') !== false) {
            [$_, $base64Data] = explode(';', $base64Data);
            [$_, $base64Data] = explode(',', $base64Data);
        }

        // strict mode filters for non-base64 alphabet characters
        if (base64_decode($base64Data, true) === false) {
            return false;
        }

        // decoding and then reeconding should not change the data
        if (base64_encode(base64_decode($base64Data)) !== $base64Data) {
            return false;
        }

        $image = base64_decode($base64Data);
        $file  = finfo_open();
        $type  = finfo_buffer($file, $image, FILEINFO_MIME_TYPE);

        return in_array($type, $mimeTypes);
    });

Inspired by Spatie media lib

foreignCitizen.passports.*.scans.*.data => 'required|base64:image/jpeg'.
Now we have a valid base64 image, we can store this safely.

I like to use Spatie media library the have a method addMediaFromBase64().
You can also do it manually converting the base64 string and storing it as a file.

If you choose to split up the process, first store the person and then the image. This is probably a bit easier to implement and less code on the backend.

0👍

I ran across this exact same problem just yesterday and finally I have a solution. Here it is:

Laravel documentation doesn’t say or at least I could not find it, but you can also access the uploaded file just like any other field, eg: $reques->uploadedFile and use it to store it like this

Storage::putFile('public', $request->uploadedFile);

So in your example you can store the scans like this:

Storage::putFile('public', $request->foreignCitizen['passports'][0]['scans'][0]);

That in general, surely you know how to apply some for loops to make it more manageable.

PS: You don’t mention if you already have sorted out the part of sending the object with the nested files to laravel, but like I said, I was in the exact same problem (vuejs/laravel), if you still haven’t solve that, I can help with that too.

Leave a comment