Multiple resize image upload with Laravel - php

I'm working to make a multi upload image to database with intervention resizer in Laravel.
This is what I'm coding right now in my controller
imgProdukProc controller:
use Illuminate\Http\Request;
use File;
use Image;
use App\imgProd;
.....
public function store(Request $request)
{
if($request->hasFile('img')){
foreach ($request->file('img') as $image) {
if ($image->isValid()) {
$img = new imgProd();
$image_name = uniqid() .'.'. $image->getClientOriginalExtension();
$path = public_path('/img/prod');
$imgx = Image::make($image->getRealPath());
$imgx->resize(360, 360, function ($constraint) {
$constraint->aspectRatio();
})->save($path.'/'.$image_name);
$img->id_prod = $request->get('id_prod');
$img->pics = 'img/prod/'.$image_name;
$date=date_create('now');
$format = date_format($date,"Y-m-d");
$img->date = $format;
$img->save();
return redirect('adminImgProd')->with('success', 'Picture successfully added ');
}
}
}
}
and this is my views
adminImgProd Views
<form enctype="multipart/form-data" action="{{url('adminImgProd')}}" method='post'>
#csrf
<div class="form-group">
<label>CODE PRODUCT</label>
<div class="input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-pencil"></span></span>
<input type="text" autocomplete="off" class="form-control" id='id_prod' name='id_prod' required="required" />
<span class="input-group-addon"><button type="button" onClick="javascript:openWindow2();">Select</button></span>
</div>
</div>
<div class="form-group">
<label>IMAGE PRODUCT</label>
<div class="input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-pencil"></span></span>
<input multiple type="file" class="form-control" name='img[]' id='file-input' required="required" /></div>
</div>
Code above is working , but somehow when I tried to upload 2 images or 3 images the only image saved both in target folder and in database is only one and it is the last one
Where is my code mistake , or just my code simply wrong from the start ?
Thank you in advance

You put your return in your foreach, so after 1 loop, it will return and exit your function :
public function store(Request $request)
{
if ($request->hasFile('img')){
foreach ($request->file('img') as $image) {
if ($image->isValid()) {
$img = new imgProd();
$image_name = uniqid() .'.'. $image->getClientOriginalExtension();
$path = public_path('/img/prod');
$imgx = Image::make($image->getRealPath());
$imgx->resize(360, 360, function ($constraint) {
$constraint->aspectRatio();
})->save($path.'/'.$image_name);
$img->id_prod = $request->get('id_prod');
$img->pics = 'img/prod/'.$image_name;
$date=date_create('now');
$format = date_format($date,"Y-m-d");
$img->date = $format;
$img->save();
}
}
return redirect('adminImgProd')->with('success', 'Picture successfully added ');
}
}

You can do the following for multiple images:
$images = $request->file('images');
foreach ($images as $key => $image) {
if ($request->hasFile('images') && $request->file('images')[$key]->isValid()) {
$path = $request->images[$key]->store('public/images');
$path = basename($path);
$image = new ProductImages();
$image->product_id = $request->get('product_id');
$image->photo = $path;
$image->save();
}
}
I hope it would helpful.

Related

PDF preview refused to connect using PHP Laravel

I'm making some kind of form be able to upload PDF file. And I also make a label to preview the file that I'm uploading. But somehow the label wont preview the file with error massage : refused to connect. Can somebody help me with it?
image form preview
So here's the PHP code for the label on the view file that I use :
<div class="form-group row">
<label class="col-md-2 col-form-label">File</label>
<div class="col-md-6">
<input type="file" name="file" id="file" class="form-control" required>
<iframe src="{{ $data['data']['files'] }}" style="width: 1000px; height:500px;" frameborder="0" id="filePreview" class="mt-2"></iframe>
</div>
<small class="text-small">{{ $errors->first('file') }}</small>
</div>
And here is the edit and update controller that I use for that view
public function edit($id)
{
$system = new SystemService();
$systemData = $system->list_badges();
$data['system'] = $systemData['data'];
$api = new SettingService();
$data['data'] = $api->get_about($id);
$data['title'] = 'Ubah Tentang Aplikasi';
$data['default'] = $this->folder;
$data['data_view'] = $this->folder . '/edit';
return view('template', $data);
}
public function update(Request $request, $id)
{
$api = new SettingService();
if ($request->hasFile('file')) {
$file = $request->file('file');
$mime = $file->getClientOriginalExtension();
$filter_file = [
'pdf',
'doc', 'docx',
'csv', 'xls', 'xlsx',
'png', 'jpg', 'jpeg',
];
if (!in_array($mime, $filter_file)) {
return back()->with('failed', 'file extention not correct');
}
$file_path = $request->file('file')->path();
$file_name = md5(date('YmdHis') . $file->getClientOriginalName()) . '.' . $file->getClientOriginalExtension();
$data['file_path'] = $file_path;
$data['file_name'] = $file_name;
}
$result = $api->update_about($id, $data);
if (isset($result['errors'])) {
return redirect($this->folder . '/' . $id . '/edit')->withErrors($result['errors'])->withInput()->with('failed', $result['message']);
}
if ($result['status'] == false) {
return redirect($this->folder . '/' . $id . '/edit')->withInput()->with('failed', $result['message']);
}
return redirect($this->folder)->with('success', $result['message']);
}
Thankyou

Upload an image and file to forum

I have searched for the SO and didn't find any article or post related to this.
How do I upload an Image using the Image Intervention and upload a normal file with in a single forum without opening a new page for the uploads.
Hope the below Answer would help someone out there.
Blade
<form action="{{route('index.store')}}" enctype="multipart/form-data" method="POST">
<div class="form-group">
<label for="resume_path">Resume</label>
<input type="file" class="form-control"
name="resume_path">
</div>
<div class="form-group">
<label for="engineer_avatar">Profile Image</label>
<input type="file" class="form-control"
name="engineer_avatar">
</div>
</form>
Controller
use Image;
use App\Engineers;
*/
public function update(Request $request, $id)
{
$this->validate($request,[
'engineer_avatar' => 'image|mimes:jpeg,png,jpg|max:2048',
'resume_path' => 'file|mimes:doc,docx,pdf|max:2048',
// dimensions:min_width=600,min_height=400'
]);
$engineers = Engineers::findOrFail($id);
if($request->hasFile('engineer_avatar')){
$image = $request->file('engineer_avatar');
$filename = time() . '.' . $image->getClientOriginalExtension();
$location = public_path('images/engineer_avatar/' . $filename);
Image::make($image)->resize(600,400)->save($location);
$engineers->avatar_path = $filename;
}
if($request->hasFile('resume_path')){
$file = $request->file('resume_path');
$file_name1 = time() . '.' . $file->getClientOriginalExtension();
$file_path = public_path('resume/engineer/');
$engineers->resume_path = $file_name1;
$file->move($file_path, $file_name1);
$engineers->save();
}
To delete the file ::
public function destroy($id)
{
$engineers = Engineers::findOrFail($id);
unlink(public_path('images/engineer_avatar/' . $engineers->avatar_path ));
unlink(public_path('resume/engineer/' . $engineers->resume_path ));
$engineers->delete();
}

Do I actually need 2 upload forms, 1 for single images and 1 for many images or can I just use 1 multi image form?

Currently, I have 2 upload forms and 2 functions, uploadImage(); and uploadAlbum();. I have been wondering if I could remove the single image form and use the multi image form for both cases. If only 1 image is selected in the multi image form, a single image would be uploaded and if more than 1 images are uploaded, an album would be uploaded.
That would make the upload view look better since it won't have 2 identical upload forms and it would only require 1 function on the back-end that would determine whether it's a single image or an album based on the amount of images uploaded.
I don't really see any downsides to it but I wanted to make sure before reworking the code.
My upload view:
<form class='uploadForm' action="{{ route('imageUpload') }}" method="POST" enctype="multipart/form-data">
<label for="name">Image Name</label>
<input class='input' type="text" name="name" placeholder="Image Name">
<label for="description">Image Description</label>
<input class='input' type="text" name="description" placeholder="Description">
<input type="file" name="image"> {{ csrf_field() }}
<button class='Submit' type="submit" name="submit">UPLOAD</button>
</form>
<form class='uploadForm' action="{{ route('albumUpload') }}" method="POST" enctype="multipart/form-data">
<label for="albumName">Album Name</label>
<input class='input' type="text" name="albumName" placeholder="Album Name">
<label for="albumDescription">Image Description</label>
<input class='input' type="text" name="albumDescription" placeholder="Description">
<input type="file" name='files[]' multiple> {{ csrf_field() }}
<button class='Submit' type="submit" name="submit">UPLOAD</button>
</form>
My uploadImage() and uploadeAlbum() functions:
public function uploadAlbum(Request $request){
$name = $request['albumName'];
$description = $request['albumDescription'];
$tag = $request['tags'];
$userId = auth()->user()->id;
$files = $request->file('files');
$path = 'storage/uploads/albums/'.$name;
$fileOriginalName = $files[0]->getClientOriginalName();
$fileName = pathinfo($fileOriginalName, PATHINFO_FILENAME);
$extension = $files[0]->getClientOriginalExtension();
$fileNameToStore = $fileName.'_'.time().'.'.$extension;
$fileNameToStore = str_replace(' ', '', $fileNameToStore);
$album = new Album();
$album->name = $name;
$album->description = $description;
$album->user_id = $userId;
$album->thumbnail = $fileNameToStore;
$album->save();
$album->tags()->attach($tag);
if(!File::exists($path)) {
File::makeDirectory(public_path($path));
}
if (is_array($files) || is_object($files)){
foreach ($files as $file){
$fileOriginalName = $file->getClientOriginalName();
$fileName = pathinfo($fileOriginalName, PATHINFO_FILENAME);
$extension = $file->getClientOriginalExtension();
$fileNameToStore = $fileName.'_'.time().'.'.$extension;
$fileNameToStore = str_replace(' ', '', $fileNameToStore);
$file->storeAs('public/uploads/albums/'.$name, $fileNameToStore);
$file->storeAs('public/uploads/albums/'.$name.'/thumbnails/', $fileNameToStore);
$thumbnailImage = InterventionImage::make('storage/uploads/albums/'.$name.'/thumbnails/'.$fileNameToStore)->fit(400, 400, function ($constraint) {
$constraint->upsize();
});
$thumbnailImage->save();
$albumImage = new AlbumImage();
$albumImage->file_name = $fileNameToStore;
$albumImage->album_id = $album->id;
$albumImage->save();
}
}
return redirect()->route('albums');
}
public function uploadImage(Request $request){
$this->validate($request, [
'name' => 'required|max:120',
'description' => 'max:120|nullable',
'image' => 'required'
]);
$name = $request['name'];
$description = $request['description'];
$tag = $request['tags'];
$userId = auth()->user()->id;
$file = $request->file('image')->getClientOriginalName();
$fileName = pathinfo($file, PATHINFO_FILENAME);
$extension = $request->file('image')->getClientOriginalExtension();
$fileNameToStore = $fileName.'_'.time().'.'.$extension;
$fileNameToStore = str_replace(' ', '', $fileNameToStore);
$request->file('image')->storeAs('public/uploads/images/',$fileNameToStore);
$request->file('image')->storeAs('public/uploads/images/thumbnails/',$fileNameToStore);
$request->file('image')->storeAs('public/uploads/images/specificImages/',$fileNameToStore);
$request->file('image')->storeAs('public/uploads/images/miniImages/',$fileNameToStore);
$thumbnail = InterventionImage::make('storage/uploads/images/thumbnails/'.$fileNameToStore )->resize(500, null, function ($constraint) {
$constraint->aspectRatio();
$constraint->upsize();
});
$thumbnail->save();
$specificImage = InterventionImage::make('storage/uploads/images/specificImages/'.$fileNameToStore )->resize(2000, null, function ($constraint) {
$constraint->aspectRatio();
$constraint->upsize();
});
$specificImage->save();
$miniImage = InterventionImage::make('storage/uploads/images/miniImages/'.$fileNameToStore )->fit(200, 200, function ($constraint) {
$constraint->upsize();
});
$miniImage->save();
$image = new Image();
$image->name = $name;
$image->description = $description;
$image->user_id = $userId;
$image->file_name = $fileNameToStore;
$image->save();
$image->tags()->attach($tag);
return redirect()->route('home');
}
This is possible of course. You would have to use the field that allows multiple
<input type="file" name="files[]" multiple />
When submitting the form you can check for if the $_POST['files'] array contains only one file. If it does, you can use the logic of a single file (image) and if it contains more you can use the logic of multiple files (album).
When you have this working you can also merge the majority of your logic and split it into multiple functions. One would be called with a foreach.

Laravel uploading multiple files in different fields in database

I was trying three images in three different fields in database..for that I was following method in controller.But the problem I'm facing is though i have three input fields it stored only two images with same name in the public folder and in database it stored value like 1 (for product_image), 4 ( for vendor_image), 9 (for user_image).
How do i properly stored the images in public folder as well as database..thanks in advance .
Here is the controller:
public function store(Request $request)
{
$product = new Product();
$files= [];
if($request->file('product_image')) $files[] = $request->file('product_image');
if($request->file('vendor_image')) $files[] = $request->file('vendor_image');
if($request->file('user_image')) $files[] = $request->file('user_image');
foreach($files as $file)
{
if(!empty($file))
{
$filename = time().'.'.$file->getClientOriginalExtension();
$file->move('images/',$filename);
}
}
$product->product_image = $filename[0];
$product->vendor_image = $filename[1];
$product->user_image = $filename[2];
$product->save();
}
here is the View part :
<div class="form-group">
<label>Product Image</label>
<input type="file" name="product_image" id="product_image" width="200px">
</div>
<div class="form-group">
<label>Feature Image</label>
<input type="file" name="vendor_image" id="vendor_image" width="200px">
</div>
<div class="form-group">
<label>Slurp Image</label>
<input type="file" name="user_image" id="user_image" width="200px">
</div>
public function imageupload(Request $request) {
$files=[];
if($request->file('profilePhoto')) $files[]=$request->file('profilePhoto');
if($request->file('fssaiPhoto')) $files[]=$request->file('fssaiPhoto');
if($request->file('panPhoto')) $files[]=$request->file('panPhoto');
foreach($files as $file){
$uniqid = Str::random(9);
$fileName = $uniqid.'.'.$file->extension();
$file->move(public_path('file'), $fileName);
$data[]=$fileName;
}
$images=new fileuploadmodels;
$images->phno=$request->phno;
$images->profilePhoto=$data[0];
$images->fssaiPhoto=$data[1];
$images->panPhoto=$data[2];
$images->save();
return response()->json([
"message"=>"photo upload success"
],201);
}
Try this:
$product_image = NULL;
$vendor_image= NULL;
$user_image= NULL;
if($request->product_image)
{
$product_image= time().'-'. $request->product_image->getClientOriginalName();
$request->product_image->move(public_path('images/'),$product_image);
}
if($request->vendor_image)
{
$vendor_image= time().'-'. $request->vendor_image->getClientOriginalName();
$request->vendor_image->move(public_path('images/'),$vendor_image);
}
if($request->user_image)
{
$user_image= time().'-'. $request->user_image->getClientOriginalName();
$request->user_image->move(public_path('images/'),$user_image);
}
$product->product_image = $product_image;
$product->vendor_image = $vendor_image;
$product->user_image = $user_image;
$product->save();

How to upload multiple image in laravel

I am trying to upload multiple images in a single row in a database table and access them in a show page.I have tried this tutorial:
laraveldaily.com/upload-multiple-files-laravel-5-4/
but there two different tables are made and a relation is established.
I want this to happen in a single table.
here is what worked best for me:
first do this in your form:
<form class="form-horizontal" enctype="multipart/form-data" method="post" action="/details">
and this for multiple selection:
<input required type="file" class="form-control" name="images[]" placeholder="address" multiple>
Now do this in your controller:
public function store(request $request) {
$input=$request->all();
$images=array();
if($files=$request->file('images')){
foreach($files as $file){
$name=$file->getClientOriginalName();
$file->move('image',$name);
$images[]=$name;
}
}
/*Insert your data*/
Detail::insert( [
'images'=> implode("|",$images),
'description' =>$input['description'],
//you can put other insertion here
]);
return redirect('redirecting page');
}
Hope this works
<form role="form" method="post" action="{{URL::to('addimage')}}" enctype="multipart/form-data">
<div class="form-group" style="padding-bottom: 15px">
<label class="col-lg-3">Upload</label>
<input class="btn btn-primary" type="file" name="files[]" > <br/>
</div>
</form>
$images = $request->file('files');
if ($request->hasFile('files')) :
foreach ($images as $item):
$var = date_create();
$time = date_format($var, 'YmdHis');
$imageName = $time . '-' . $item->getClientOriginalName();
$item->move(base_path() . '/uploads/file/', $imageName);
$arr[] = $imageName;
endforeach;
$image = implode(",", $arr);
else:
$image = '';
endif;
DB::table('fooo')->insert(
array(
'image' => $image
)
);
Session::flash('message', 'Image upload successfully successfully');
return redirect('/addimage');
this can also be achieved with
foreach ($request->file('files') as $index => $item) {
$path = $request->files[$index]->store('images');
}
html
<input type="file" name="images[]" multiple>
controller : store folder storage
foreach ($request->file('images') as $imagefile) {
return $imagefile->store('images','public');
}
This one works for me.
Form:
<form class="form-horizontal" enctype="multipart/form-data" method="post" action="/details">
and this for multiple selection image:
<input required type="file" class="form-control" name="image[]" placeholder="address" multiple>
Now do this in Our Model:
protected fillable = ['producd','image', ];
Now do this in Our controller:
public function store(Request $request)
{
$image = array();
if($file = $request->file('image')){
foreach($file as $file){
$image_name = md5(rand(1000,10000));
$ext = strtolower($file->getClientOriginalExtension());
$image_full_name = $image_name.'.'.$ext;
$uploade_path = 'uploads/images/';
$image_url = $uploade_path.$image_full_name;
$file->move($uploade_path,$image_full_name);
$image[] = $image_url;
}
Image::insert([
'image' => implode('|', $image),
'producd' => $request->producd,
]);
return redirect('/image.index'));
}
}
$images = array();
if ($request->hasFile('gallery_image')) {
$files = $request->file('gallery_image');
foreach ($files as $file) {
$image_name = md5(rand(1000, 10000));
$ext = strtolower($file->getClientOriginalExtension());
$image_full_name = $image_name . '.' . $ext;
$file->move('Your image path here',
$image_full_name);
$images[] = $image_full_name;
}
}
$house->gallery_image = json_encode($images);

Categories