1

i am trying to upload multiple images.after selecting images when i submit the form then i got this--

"{message: "The given data was invalid.", errors: {media: ["The media field is required."]}}"

it looks like the "media[]" field is not getting the value. But i got the data in media array(see the image)

vue devtool

how can i solve this

my productController code-

`public function store(Request $request)
    {
        $this->validate($request, [
            'title' => 'required|max:255',
            'price' => 'required|integer',
        
        'media'=>'required',

    ]);


    $product = Product::create([
        'title' => $request->title,
        'price' => $request->price,
        
    ]);

    if ($request->image) {
        $imageName = time() . '_' . uniqid() . '.' . $request->image->getClientOriginalExtension();
        $request->image->move(public_path('storage/product'), $imageName);
        $product->image = '/storage/product/' . $imageName;
        $product->save();
    }

    foreach($request->media as $image){
        $from = public_path('tmp/uploads/'.$image);
        $to = public_path('product_images/'.$image);

        File::move($from, $to);
        $product->images()->create([
          'name' => $image,
        ]);
      }
  

    return response()->json($product, 200);
}`

my imageController code is--

public function store(Request $request){

    $path = public_path('tmp/uploads');

    if (!file_exists($path)) {
      mkdir($path, 0777, true);
    }

    $file = $request->file('image');

    $name = uniqid() . '_' . trim($file->getClientOriginalName());

    $file->move($path, $name);

    return ['name'=>$name];
  }

  public function getImages(Product $product){
    $images = $product->images;
    return ['media'=>$images];
  }

api.php--

Route::resource('product','ProductController');
Route::post('/upload', [ImageController::class, 'store'])->name('upload');
Route::get('/media/{product}', [ImageController::class, 'getImages'])->name('product.images');

vue component---

import axios from 'axios'
export default {
    data(){
        return{
            media:[],
            loading:false,
        }
    },
    methods:{
        async fileChange(event){
            this.loading=true
            let files = event.target.files
            for(var i=0; i < files.length; i++){
                let formData = new FormData
                let url = URL.createObjectURL(files[i])
                formData.set('image', files[i])
                const {data} = await axios.post(this.server, formData)
                
            this.media.push({url:url, name:data.name, size:files[i].size, type:files[i].type});
                
                
        }
        this.loading=false
        this.media_emit()
    },
    remove(index){
        this.media.splice(index,1)
        this.media_emit()
    },
    media_emit(){
        this.$emit('media',this.media)
    }
},
mounted() {
    this.$emit('media',this.media)
},
2
  • You are appending image as the key in the FormData in the vue component while the validation rules is looking for a key media hence you are getting the validation error. Also you are newing up FormData within for loop - instead move let formData = new FormData out of the for loop Commented Jun 16, 2022 at 18:53
  • not working. sorry Commented Jun 17, 2022 at 13:15

1 Answer 1

1

You could try:

$this->validate($request, [
    'title' => 'required|max:255',
    'price' => 'required|integer',        
    'media.*' => 'required|mimes:jpg,jpeg,png|max:20000']);

It also validates it is a an image with those extensions.

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

5 Comments

i am following this tutorial.dev.to/simodev/… he didn't use 'media.*'. i tried your solution. not working. thanks
did you try the answer?
yes. it is showing---SQLSTATE[42S22]: Column not found: 1054 Unknown column 'media' in 'field list'
Well, now the validation is passing, now you have to check your DB, maybe a migration is missing
now showing -- {message: "Invalid argument supplied for foreach()", exception: "ErrorException",…} . it cant recognize the "media"

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.