dimanche 3 mai 2020

Vue / Laravel: How to validate files uploaded from the frontend?

I have an image uploader on my Vue app that takes multiple files. I want to ensure they are images and of a certain size and if not, obviously don't upload the files and have the frontend display the error. Right now, the route it hits in the controller loos like this:

   public function uploadAssets(UploadAssetsFormRequest $request)
    {
        if ($request->hasFile('file')) {
            $files = $request->file('file');
            $stack = [];
            foreach ($files as $file) {
                $fileName = Storage::put('/check/', file_get_contents($file->getRealPath()), ['visibility' => 'public']);
                array_push($stack, $fileName);
            }
            return response()->json($stack);
        }
    }

My Form Request is below and has the validation but I don't know how to apply that in the controller.

UploadAssetsFormRequest

<?php

namespace App\Http\Requests\Admin;

use Illuminate\Foundation\Http\FormRequest;

class UploadAssetsFormRequest extends FormRequest
{

    public function authorize()
    {
        return true;
    }

    public function rules()
    {
        return [
            'files.*' => 'required|image|max:1000',
        ];
    }

    public function messages()
    {
        return [
            'files.*.max'   => 'The image is too large',
            'files.*.image' => 'Only image files are allowed.',
        ];
    }
}


via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire