php - "Call to a member function getClientOriginalName() on array" error when uploading multiple files ← (PHP, Laravel, HTML)

I have a form that accepts multiple inputs, part of which are uploads. The form accepts other forms of input but I get the error when I try to upload files.

The part of the form for the uploads is:

{!! Form::label('downloadable_files', 'Downloadable files', ['class' => 'control-label']) !!}
{!! Form::file('downloadable_files[]', [
                    'multiple',
                    'class' => 'form-control file-upload',
                    'data-url' => route('admin.media.upload'),
                    'data-bucket' => 'downloadable_files',
                    'data-filekey' => 'downloadable_files',]) !!}

The controller method is:

public function store(StoreLessonsRequest $request)
    {
        if (! Gate::allows('lesson_create')) {
            return abort(401);
        }
        $request = $this->saveFiles($request);
        $lesson = Lesson::create($request->all()
        + ['position' => Lesson::where('course_id', $request->course_id)->max('position') + 1]);

        foreach ($request->input('downloadable_files_id', []) as $index => $id) {
        $model = config('laravel-medialibrary.media_model');
        $file = $model::find($id);
        $file->model_id = $lesson->id;
        $file->save();
        }

      return redirect()->route('admin.lessons.index', ['course_id' => $request->course_id]);}

The savesFiles() method is in a FileUploadTraid.php:

public function saveFiles(Request $request)
{
    if (! file_exists(public_path('uploads'))) {
        mkdir(public_path('uploads'), 0777);
        mkdir(public_path('uploads/thumb'), 0777);
    }

    $finalRequest = $request;

    foreach ($request->all() as $key => $value) {
        if ($request->hasFile($key)) {
            if ($request->has($key . '_max_width') && $request->has($key . '_max_height')) {
                // Check file width
                $filename = time() . '-' . $request->file($key)->getClientOriginalName();
                $file     = $request->file($key);
                $image    = Image::make($file);
                if (! file_exists(public_path('uploads/thumb'))) {
                    mkdir(public_path('uploads/thumb'), 0777, true);
                }
                Image::make($file)->resize(50, 50)->save(public_path('uploads/thumb') . '/' . $filename);
                $width  = $image->width();
                $height = $image->height();
                if ($width > $request->{$key . '_max_width'} && $height > $request->{$key . '_max_height'}) {
                    $image->resize($request->{$key . '_max_width'}, $request->{$key . '_max_height'});
                } elseif ($width > $request->{$key . '_max_width'}) {
                    $image->resize($request->{$key . '_max_width'}, null, function ($constraint) {
                        $constraint->aspectRatio();
                    });
                } elseif ($height > $request->{$key . '_max_width'}) {
                    $image->resize(null, $request->{$key . '_max_height'}, function ($constraint) {
                        $constraint->aspectRatio();
                    });
                }
                Image::make($file)->resize(320, 150)->save(public_path('uploads') . '/' . $filename);
                $finalRequest = new Request(array_merge($finalRequest->all(), [$key => $filename]));
            } else {
                ***$filename = time() . '-' . $request->file($key)->getClientOriginalName();***
                $request->file($key)->move(public_path('uploads'), $filename);
                $finalRequest = new Request(array_merge($finalRequest->all(), [$key => $filename]));
            }
        }
    }

    return $finalRequest;
}

}

There is a part of the form that accepts single uploads, but the part for multiple uploads doesn't seem to be working. I keep getting the errors:

Call to a member function getClientOriginalName() on array

in FileUploadTrait.php line 50
at LessonsController->saveFiles(object(StoreLessonsRequest))
in LessonsController.php line 156
at LessonsController->update(object(StoreLessonsRequest), '1')

Update: The line with the error in FileUploadTrait.php is in bold (or with asterisks.

Answer



Solution:

-in your case you are not giving  only the name of the file but all the 
  inforamtions of the file make a dd($request->file($key)) and search for the 
  your filename for example : ex.pnj and access it

that's my code : in my controller

public function uploadFiles(Request $request){
  $request->validate([
        'files'=>'required',
        'files.*'=>'image|mimes:jpeg,png,jpg,svg|max:2048'
  ]);
          $files = $request->file('files');

        foreach ($files as $file) {
            $name = time(). $file->getClientOriginalName();
            $file->move('gallery',$name);
            Photo::create([
                'name'=>$name,
                'user_id'=>auth()->user()->id
            ]);
        }
        flashy()->success('le contenu a bien Г©tГ© ajoutГ©.');
        return back();
    }

in my html file

<form action="{{route('upload')}}" method="POST" 
      enctype="multipart/form-data">
    @csrf
    <input
            type="file"
            multiple
            id="btn-gallery"
            name="files[]"
            label="DГ©posez les fichiers ici ou cliquez pour les tГ©lГ©charger.."
            help="TГ©lГ©chargez les fichiers ici et ils ne seront pas envoyГ©s immГ©diatement"
            is="drop-files"
    />
    <button type="submit" id="btn-upload" class="btn btn-primary mt-1">tГ©lГ©charger</button>
</form>

Answer



Solution:

in your store method

 $files=$request->file('your input name');
 
 $request = $this->saveFiles($files)

in your function :

public function saveFiles($files){
  foreach ($files as $file) {
        $name = time(). $file->getClientOriginalName();
        $file->move('yourFolderStorageName',$name);

}

}

Source