Leff7's avatar

Laravel 5.1 Ajax file upload

I am trying to upload multiple files with AJAX using jFiler package. I have a form where users upload files and have a preview for images and videos that are uploaded. And then when the user later fills up the rest of the form, and submits it, I want to save the paths of the files in the database, with the id of the article they belong to. I am therefore saving file path to session in my controller and saving it to DB like this:

 //save article to DB
 public function store(Create $request) {
 $slug = str_slug($request['name']);
 $count = Article::where('slug', 'like', '%'.$slug.'%')->count();

 if($count)
     $slug = $slug .'-'. $count;

  $article = Article::create(array_merge($this->fillobject($request), $data));

  //store external media for the article
  $externalMedia = ExternalMedia::create([
       'url' => $request->input('external_media'),
       'article_id' => $article->id
        ]);


    //if files are uploaded store call fileUpload and store files
    $this->fileUpload(Session::get('filePath'), $article->id);

    return Redirect::route('admin.articles.show',['id'=>$article->id]);
 }

  public function fileUpload($files, $id) {

  $articleMedia = [];
  $articleMediaFiles = Media::where('article_id', $id)->get(['path']);

  foreach($articleMediaFiles as $articleMediaFile) {
      $articleMedia[] = $articleMediaFile->path;
   }

  foreach($files as $file) {
      $oldPath = explode('articles/', $file);
      $directoryPath = $oldPath[0].'articles/'.$id;
      $newPath =  explode('public/',   $oldPath[0].'articles/'.$id.'/'.$oldPath[1]);

      if(!File::exists($directoryPath))
           File::makeDirectory($directoryPath, 0755, true);



      if(!in_array($newPath[1], $articleMedia))
           Media::create(['path' => $newPath[1], 'article_id' => $id]);

           Image::make($file)->resize(100, 100)->save($newPath[1]);
      }
   }

   public function ajaxUpload() {
       $name = "";
       $path = public_path('files/uploads/articles/');

        if (Input::hasFile('file')) {
              $files = Input::file('file');

        foreach($files as $file){
             $filePath[] = $path.$file->getClientOriginalName();
             Image::make($file)->resize(100, 100)->save($path.'/'.$file->getClientOriginalName());
        }
         Session::put('filePath', $filePath);
          return json_encode($filePath);
       }
    }

My issue with this code is that I only save one file path to DB when uploading multiple files.

0 likes
1 reply

Please or to participate in this conversation.