Multiple Image Uploading using Image Intervention. I tried to upload multiple image but could not as i don't know how, any help would be appreciated

Viewed 126

This is my Controller can anybody tell me what I have to add more so that I can add multiple images to my database I was instructed to use loops but I don't exactly know where to use so I have added my controller which allows me to upload single image but its no use for uploading multiple images. The second code is my blade file means my view where I created a form and the input type of my image is 'file' and name is 'filename' And I have used image intervention of Laravel so any help would be appreciated.

public function upload(){
        $images = ImageModel::all();
        return view('uploadimage',compact('images'));
    }

    public function uploadImage(Request $req){
        $this->validate($req, [
                'filename' => 'required',
            'filename.*' => 'images|mimes:jpeg,png,jpg,gif,svg|max:2048'
            ]);
  
        $title = $req->title;
        $slug = Str::of($title)->slug('-');
        $alttext = $req->alttext;

        $originalImage= $req->file('filename');
        $thumbnailImage = Image::make($originalImage);

        $thumbnailPath = public_path().'/thumbnail/';
        $originalPath = public_path().'/images/';

        $temp = $originalImage->getClientOriginalName();
        $temp_ext = explode(".",$temp);
        $ext = end($temp_ext); 

        $filename = time().".".$ext;
        

        $thumbnailImage->save($originalPath.$filename);
        $thumbnailImage->resize(150,150);
        $thumbnailImage->save($thumbnailPath.$filename); 

        $imagemodel= new ImageModel();
        $imagemodel->title=$title;
        $imagemodel->slug=$slug;
        $imagemodel->alttext=$alttext;
        $imagemodel->filename=$filename;
        if($imagemodel->save()){
            return redirect()->back()->with('msg','Succesfully Uploaded'); 
        }
    }

And my blade.php file is also included.

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <title>Image Upload</title>
    <style>
        img {
        border-radius: 2px;
        padding: 3px;
        width:200px; 
        height:100px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h2>Image Upload Using Intervention</h2>
        @if(Session::has('msg'))
            <div class="alert alert-success">
                {{ Session::get('msg')}}
            </div>
        @endif

        @if (count($errors) > 0)
            <div class="alert alert-danger">
                <strong>Whoops!</strong> There were some problems with your input.<br><br>
                <ul>
                @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
                </ul>
            </div>
        @endif
        
        <form action="{{URL::to('upload-image')}}" method="post" enctype="multipart/form-data">
        {{csrf_field() }}
            <div class="form-group">
                <label for="">Title</label>
                <input type="text" class="form-control" name="title" id=" ">
            </div>

            <div class="form-group">
                <label for="">Image</label>
                <input type="file" multiple class="form-control" name="filename" id="imgInp">
                <img width= " 200px"id="blah" src="#" alt="your image" />
            </div>

            <div class="form-group">
                <label for="alttext">AltText</label>
                <input type="text" class="form-control" name="alttext" id=" ">
            </div>

            <div class="form-group">
                <button type="submit" class="btn btn-primary">Upload</button>
            </div>
        </form>

        <hr>
        <div class="container">
            <div class="card">
                <div class="card-header">
                    <h2>Uploaded Images</h2>
                </div>

                <div class="card-body">
                    @if($images)
                        @foreach($images as $i)
                            <img src="{{ asset('images/'. $i->filename)}}" alt="">
                            <!-- {{ $i->filename}} -->
                        @endforeach
                    @endif
                </div>
            </div>
        </div>
    </div>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script>

        function readURL(input) {
            if (input.files && input.files[0]) {
            var reader = new FileReader();
            
            reader.onload = function(e) {
            $('#blah').attr('src', e.target.result);
            }
            
            reader.readAsDataURL(input.files[0]); // convert to base64 string
            }
        }
        $("#imgInp").change(function() {
            readURL(this);
        });
    </script>
</body>
</html>
1 Answers

This one is without using jquery ajax

//controller
$files = $request->file('images'); //get all files

$images = [];
foreach($files as $file){
    $images[] = [ 'image_name' => $this->storeImage($file,'your_path') ];
}

/*storeImage function could be in same controller or a separate trait file, 
if you want to reuse image upload functionality in other controller(for image upload)*/

public function storeImage($file, $path) 
{
    $name = str_replace(" ", "_", $file->getClientOriginalName());
    $file->storeAs($path , $name);
    return $fileName;
}

ImageModel::insert($images); //save all record at once

//in html code change this line

<input type="file" multiple class="form-control" name="filename[]" id="imgInp">
  • And for better practice laravel has Form Request, A separate request class containing validation logic. To create one you can use below Artisan command:
    php artisan make:request AnyNameRequest
Related