Home > OS >  Multiple image upload in laravel
Multiple image upload in laravel

Time:11-11

i have this code in my controller that can make me upload successfully just one file , and i want to upload many files in once time :

public function store(Request $request, $id) {
    $request->validate([
            'image' => 'required',
    ]);

    $listing = Listing::findOrFail($id);
    $image = new Listingimage();

    if ($request->hasFile('image')) {
        $file = $request->file('image');
        $extention = $file->getClientOriginalExtension();
        $filename = time() . '.' . $extention;
        $file->move('assets/images/listingimages/', $filename);
        $fileOriginalName = $file->getClientOriginalName();
    }

    $image->listing_id = $id;
    $image->image_url = $filename;
    $image->nom_image = $fileOriginalName;
    $image->save();
    return redirect()->back();
}

i use also this input :

<form action="{{ route('Listingimages.store', $listing->id) }}" method="POST" enctype="multipart/form-data">
    <input type="hidden" name="_method" value="PUT" />
    {{csrf_field()}}
    {{method_field('PUT')}}
    <label>  Insert image</label>
    <input type="file" name="image" id="files" class="form-control" multiple>

so , how can i upload many files in once time ?

CodePudding user response:

change input name

<input type="file" name="image[]" id="files" class="form-control">

controller

   public function store(Request $request, $id) {
        $request->validate([
            'image' => 'required',
        ]);

        $listing = Listing::findOrFail($id);
        if ($request->hasFile('image')) {
            foreach($request->file('image') as $file)
            {
                $image = new Listingimage();
                $file = $request->file('image');
                $extention = $file->getClientOriginalExtension();
                $filename = time() . '.' . $extention;
                $file->move('assets/images/listingimages/', $filename);
                $fileOriginalName = $file->getClientOriginalName();
                $image->listing_id = $id;
                $image->image_url = $filename;
                $image->nom_image = $fileOriginalName;
                $image->save();
            }

        }
        return redirect()->back();

    }
  • Related