Cannot use object of type Illuminate\Http\UploadedFile as array - 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('test#gmaIL.com')->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;
}

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)

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);
}
}

Related

Laravel download image

I have a function to add an image, and upon successful addition in the database, we have a path like public/images/asd.png. The question is how to make sure that when added to the name of the picture, an ID is added, and we have something like public/images/asd1.png, public/images/asd2.png, etc.
function in Model
public function getOriginImageUrl()
{
return $this->attributes['image'];
}
public function getImageAttribute($value)
{
return Storage::exists($value) ? Storage::url($value) : null;
}
function in Controller
if ($request->hasFile('image')) {
$file = $request->file('image');
$blog->image = $file->storeAs('public/images', $file->getClientOriginalName());
}
Instead of id you can combine time() with image name.
if ($request->hasFile('image')) {
$file = $request->file('image');
$namewithextension = $file->getClientOriginalName(); //Name with extension 'filename.jpg'
$name = explode('.', $namewithextension)[0]; // Filename 'filename'
$extension = $file->getClientOriginalExtension(); //Extension 'jpg'
$uploadname = $name. '-' .time() . '.' . $extension;
$blog->image = $file->storeAs('public/images', $uploadname);
}

Laravel upload gifs

i am uploading gif for my posts in laravel but gif is like an image its not moving or something like this
<?php
if($request->hasFile('gif')){
$gif = $request->file('gif');
$gif_filename = time() . '.' . $gif->getClientOriginalName();
$gif_location = public_path('/images/' . $gif_filename);
Image::make($gif)->save($gif_location);
}
$post->gif = $gif_filename;
$post->save();
?>
here is the code what I am using I think everything is kinda correct
I use this method
if(Input::hasFile('imagen')) {
$time = Carbon::now()->format('Y-m-d');
$image = $request->file('imagen');
$extension = $image->getClientOriginalExtension();
$name = $image->getClientOriginalName();
$fileName = $time."-".$name;
$image->move(storage_path(),$fileName);
}
Please try this and let me know how it works :)
An easy way to update and save is to do it like this:
public function store(Request $request)
{
$imgLocation = Storage::disk('public')->put(time() . '.' . $request->file('image')->getClientOriginalName(), $request->gif), $request->file('gif'));
// This would save it to the gifs table if you need something like it, otherwise skip this creation
$gif= Gif::create([
'name' => $request->name,
'path' => $imgLocation
]);
if ($gif) {
return response()->json("Success!");
}
return response()->json("Error!"); // or you return redirect()...
}
$image = $request->file('image');
if(isset($image)) {
if($image->getClientOriginalExtension()=='gif'){
$image = $request->file('image');
$extension = $image->getClientOriginalExtension();
$name = $image->getClientOriginalName();
$fileName = 'exerciseimages'."-".$name;
$image->move('storage/courseimages/',$fileName);
}
else{
$fileName = 'exerciseimages'.'-'.uniqid().'.'.$image->getClientOriginalExtension();
if(!Storage::disk('public')->exists('courseimages')){
Storage::disk('public')->makeDirectory('courseimages');
}
$amenitiesimg = Image::make($image)->resize(250,250)->stream();
Storage::disk('public')->put('courseimages/'.$fileName, $amenitiesimg);
}
}
else {
$fileName = 'default.png';
}

I am trying to upload multiple images in laravel and facing issues as the same image is uploaded each time?

The problem is that my loop only running and uploading the same first pic each time rather than uploading each other in a row one after one!
Here is my code of the form
{!! Form::file('photos[]', ['roles' => 'form', 'class' => 'form-control-file','multiple' => true]) !!}
Here is my code of the controller
$files=$request->file('photos');
foreach ($files as $file) {
$insert = new Images;
$insert->youth_fashion_images_category = $request->selectproduct;
$destinationPath = 'uploads/products';
$imageName = 'uploads/products/'.time().'.'.$file->getClientOriginalExtension();
$insert->Save();
$uid = $insert->id;
$file->move($destinationPath,$imageName);
$image = array(
'youth_fashion_images_img' => $imageName
);
Images::where('youth_fashion_images_id',$uid)->update($image);
}
return redirect('adminpanel/viewimages');
Try this code :
if($request->hasfile('photos'))
{
foreach($request->file('photos') as $image)
{
$destinationPath = 'uploads/products';
$imageName = 'uploads/products/'.time().'.'.$image->getClientOriginalExtension();
$image->move($destinationPath,$imageName);
$insert = new Images;
$insert->youth_fashion_images_category = $request->selectproduct;
$insert->youth_fashion_images_img = $imageName;
$insert->Save();
}
}
You should try this code.
if($request->hasfile('photos')) {
foreach($request->file('photos') as $image)
{
$destinationPath = 'uploads/products';
$name = 'uploads/products/'.time().'.'.$image->getClientOriginalName();
$image->move($destinationPath, $name);
$data[] = $name;
}
}
$insert= new Images;
$insert->youth_fashion_images_img = json_encode($data);
$insert->save();
json_encode to insert the multiple image names in one row.
So add $name in array $data[] = $name;.
I hope this will helps.

Laravel Job Mail files failed to open the file

I wanted to add a job to send a mail to a big list of adresses; but i get an exception
Swift_IoException: Unable to open file for reading
I method was working perfectly without the job but now when i use a dispatch job with database i get this error. someone knows why i get the exception ?
When i use this directly in the controller the attachement work :
if($request->uploads){
foreach($request->uploads as $file) {
$files[] = [
'file' => $file->getRealPath(),
'options' => [
'mime' => $file->getClientMimeType(),
'as' => $file->getClientOriginalName()
],
];
}
}else{
$files = null;
}
Mail::to($emails)->send(new MassiveEmail($subject , $bodyMessage , $files));
But when i use this, it's doesn't work :
$job = (new SendEmailMassiveJob($emails , $subject , $bodyMessage , $files))
->delay(Carbon::now()->addSeconds(10));
dispatch($job);
Here my job class :
public function handle()
{
$emails = $this->emails;
$subject = $this->subject;
$bodyMessage = $this->bodyMessage;
$files = $this->files;
foreach ($emails as $email){
Mail::to($email)->send(new MassiveEmail($subject , $bodyMessage , $files));
}
}
Here my mail class who generate an error when i attach the files:
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');
if($files){
foreach($files as $file) {
$email->attach($file['file'],$file['options']);
}
}
return $email;
}

Laravel and DropzoneJS file uploaded with different extension

I created a form here with Laravel and DropzoneJS and I tried uploading a Gimp file (.xcf) and when it is uploaded it is saved in S3 as the following
<random-name>.
without the "xcf" extension just random name ending with a dot.
Also, I created a text file and renamed it to test.xcf when I tried uploading that file it was uploaded with the .txt extension.
Here is my UploadController.php which handles the upload:
<?php
namespace App\Http\Controllers;
use App\Upload;
use Illuminate\Http\Request;
class UploadController extends Controller
{
public function upload(Request $request)
{
$originalName = $request->file('file')->getClientOriginalName();
$fileSize = $request->file('file')->getClientSize();
$path = $request->file('file')->store('documents');
$explode = explode('documents/', $path);
$name = $explode[1];
$uniqueId = $this->generateUniqueId();
$upload = new Upload();
$upload->unique_id = $uniqueId;
$upload->name = $name;
$upload->path = $path;
$upload->original_name = $originalName;
$upload->size = $fileSize;
if ($upload->save())
{
return response()->json([
'original_name' => $originalName,
'size' => $fileSize,
'url' => env('AWS_URL') . $path,
'id' => $uniqueId,
'status' => 'OK'
]);
}
return response()->json(['status' => 'BAD', 'message' => 'There was a problem saving your file.']);
}
public function generateUniqueId()
{
$result = '1';
$result .= rand(100000000, 999999999);
while(Upload::where('unique_id', '=', $result)->first())
{
$result = '1';
$result .= rand(100000000, 999999999);
}
return $result;
}
}
I've got no idea why it's doing that.
I suggest, you generate your own hash for filename, like I do in this code:
$file = $request->file('csv');
$path = $file->storeAs(
'csv',
md5($file->getClientOriginalName()) . $file->getClientOriginalExtension(),
's3'
);
You can also add uniqid() to md5 input
If you're using laravel 5+ then you should get the extension also using this.
$extension = $file->getClientOriginalExtension();
This will work fine.

Resources