1

So I am tinkering with an image uploader which will preview the image before uploading.

There are restrictions in place to allow just jpg, jpeg or png image formats, however, the error messages aren't being returned and I have tried a number of methods Please see my code below:

<template>
    <div class="row">
        <div class="col-md-12">
            <img :src="image" class="img-responsive" alt="">
        </div>
        <div class="col-md-8">
            <input type="file" v-on:change="onFileChange" class="form-control">
        </div>
        <div class="col-md-4">
            <button class="btn btn-success btn-block" @click="upload">Upload</button>
        </div>
    </div>
</template>

This is being designed using Vue and Laravel. I am literally 1 day into learning Vue so please let me know if I have missed a vital part you need to look at (such as the route/controller)

<script>
    export default {
        data() {
            return {
                image: ''
            }
        },

        methods: {
            onFileChange(e) {
                let files = e.target.files || e.dataTransfer.files;
                if (!files.length)
                    return;
                this.createImage(files[0]);
            },
            createImage(file) {
                let reader = new FileReader();
                let vm = this;
                reader.onload = (e) => {
                    vm.image = e.target.result;
                };
                reader.readAsDataURL(file);
            },
            upload(){
                axios.post('/api/upload',{image: this.image})
                    .then(response => {

                    });
            }
        }
    }
</script>

Please see the controller below:

public function upload(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'image' => 'required|image64:jpeg,jpg,png'
        ]);
        if ($validator->fails()) {
            return response()->json(['errors'=>$validator->errors()]);
        } else {
            $imageData = $request->get('image');
            $fileName = Carbon::now()->timestamp . '_' . uniqid() . '.' . explode('/', explode(':', substr($imageData, 0, strpos($imageData, ';')))[1])[1];
            Image::make($request->get('image'))->save(public_path('images/').$fileName);
            return response()->json(['error'=>false]);
        }
    }
2
  • what you returning if you get any error message from laravel ? Commented Nov 7, 2017 at 11:59
  • @user, I have added the controller in for you to refer to. I have also added a custom message within validation.php: 'image64' => 'The :attribute must be a file of type: :values.', Commented Nov 7, 2017 at 12:04

2 Answers 2

3

Validate form and return error from laravel controller as

private function validateForm($advsearch){
    $validator = Validator::make($advsearch, [
        'fname' => 'required',
    ]);
    return $validator;
}

public function submitForm(Request $request){
    $validator = $this->validateForm($request->all());
    if ($validator->fails()) {
        return response()->json(['isvalid'=>false,'errors'=>$validator->messages()]);
    }
    .....
    .....
}

And display in vue by binding

<div>{{errors.fname?errors.fname[0]:''}}</div>

if you already bind errors in vue data

   data() {
        return {
            errors:[],
            image: ''
        }
   },

And update it after submit and if you get any error

  axios.post('/api/upload',{image: this.image})
     .then(response => {
         if(response.isValid == false){
            this.errors = response.errors;
         }
  });

in your update you can check errors exist or not by if(response.body.errors !== undefined){

Sign up to request clarification or add additional context in comments.

16 Comments

in your update you can check errors exist or not by if(response.body.errors !== undefined){
Thanks for the answer, it's throwing an error currently of: Uncaught (in promise) TypeError: Cannot read property 'isValid' of undefined
yes because I used json(['isvalid'=>false,'errors'=>$validator->messages()]) in controller
I added this within the controller also?
use [0] like this {{errors.fname?errors.fname[0]:''}} for fname
|
0

response.data.isValid use this instead of response.isValid in uppercase

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.