Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot use object of type Illuminate\Http\UploadedFile as array

Tags:

laravel

I try to send attachement files but i get

Cannot use object of type Illuminate\Http\UploadedFile as array

I use laravel 5.4

Someone know why i'm getting this error ?

( I don't upload the file into a directory, i just want to send the file who was requested on my controller )

Hope someone could help , best regards :)

Here my controller :

public function postSendMassive(Request $request){

        $files = $request->file('uploads');

        $emails = Structure::where('type_structure_id', 4)->pluck('adresse_email_structure');

        $subject = $request->subject;
        $bodyMessage = $request->texte;

        foreach($files as $file) {
            $files[] = [
                'file' => $file->getRealPath(),
                'options' => [
                    'mime' => $file->getClientMimeType(),
                    'as'    => $file->getClientOriginalName()
                ],
            ];
        }

        Mail::to('[email protected]')->send(new MassiveEmail($subject , $bodyMessage , $files));

        return back()->with('status', "Email envoyé");

    }

here my build mail :

public function build()
    {

        $subject = $this->subject;
        $bodyMessage = $this->bodyMessage;
        $files = $this->files;

        $email =  $this->markdown('email.MassiveMail',compact('bodyMessage'))
            ->subject($subject.'-'.'FFRXIII Licences & Compétitions');


        foreach($this->files as $file) {
            $email->attach($file['file'],$file['options']);
        }

        return $email;
    }
like image 780
Mathieu Mourareau Avatar asked Dec 02 '17 16:12

Mathieu Mourareau


2 Answers

This is because $request->file('uploads') returns an object and you're trying iterate over it with foreach

If you want to upload multiple files, make sure you're doing something like this:

<input type="file" name="uploads[]" multiple />

And iterate over uploaded files:

foreach ($request->uploads as $file)
like image 155
Alexey Mezenin Avatar answered Nov 20 '22 14:11

Alexey Mezenin


This works!

    if($request->hasFile('files')){
        
        foreach ($request->files as $file) {
            
            //get file name with extenstion
            $fileNameWithExt = $file->getClientOriginalName();

            //get just filename
            $fileName = pathinfo($fileNameWithExt, PATHINFO_FILENAME);

            //get extension
            $extension = $file->getClientOriginalExtension();

            //file to store
            $fileNameToStore = $fileName.'_'.time().'.'.$extension;

            //upload to store
            $path = $file->storeAs('${your_storage_path}', $fileNameToStore);

            
        }    
        
    }
like image 3
Francis Umeanozie Avatar answered Nov 20 '22 12:11

Francis Umeanozie