Laravel uploading multiple files in different fields in database - php

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

Related

I have 4 rows and 4 columns each row display images from different tables how to update any images in laravel framework

update function of laravel framework
public function update(Request $request, $id)
{
if(isset($_POST['commer']))
{
$commercial = BestCommercialPhoto::findOrFail($id);
$input = $request->all();`enter code here`
if($file = $request->file('file'))
{
$name = time().$file->getClientOriginalName();
$file->move('images',$name);
$input['file'] = $name;
}
$commercial->update($input);
}
elseif(isset($_POST['fash']))
{
$fashion = BestFashionPhoto::findOrFail($id);
if($file = $request->file('file')){
$name = time().$file->getClientOriginalName();
$file->move('images',$name);
$input['file'] = $name;
}
$fashion->update($input);
}
elseif(isset($_POST['wed']))
{
$wedding = BestWeddingPhoto::findOrFail($id);
if($file = $request->file('file')) {
$name = time().$file->getClientOriginalName();
$file->move('images',$name);
$input['file'] = $name;
}
$wedding->update($input);
}
elseif(isset($_POST['make']))
{
$making = BestMakingPhoto::findOrFail($id);
if($file = $request->file('file'))
{
$name = time().$file->getClientOriginalName();
$file->move('images',$name);
$input['file'] = $name;
}
$making->update($input);
}
else
{
return "Not Working Properly";
}
}
This is code for edit
public function edit($id)
{
$commercial = BestCommercialPhoto::findOrFail($id);
return view('admin.bestPhoto.edit_comm',compact('commercial'));
}
Below is HTML code for edit page. I am not able to update if I click on 2nd row which contains[enter image description here][1] 4 fashion category image. If I click to update Fashion category image its displays the 1st-row image how to update the images of different rows
<form method="post" action="/admin/bestPhoto/{{$commercial->id}}" enctype="multipart/form-data">
<input type="hidden" name="_method" value="PATCH">
{{ csrf_field()}}
<div class="card shadow-lg">
<div class="card-body">
<div class="form-group">
<div class="text-center">
<img class="img-fluid" src="/images/{{$commercial->file}}">
</div>
</div>
<div class="form-group">
<div class="text-center">
<input type="file" name="file" required>
</div>
</div>
<div class="form-group" style="width:25%">
<div class="text-center" >
<button name="commer" class="btn btn-outline-primary" type="submit"
style="width: 50%;">Save
</button>
</div>
</div>
</div>
</div>
</form>

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

Multiple resize image upload with Laravel

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.

Call to a member function getClientOriginalName() on array laravel

I'm trying to post an image from a one to many relationship while also doing the CRUD (create part), but I am having some trouble doing it. I keep on getting this error,Call to a member function getClientOriginalName() on array, whenever I try to use associate to define the relationship together with user_info with user_image table. So what should I do?
Here are my codes:
createController:
public function create1(){
return view('create1');
}
public function store1(Request $request){
$this->validate($request, [
'input_img' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
$user_info = Session::get('data');
$UserImage = new UserImage($request->input()) ;
if($file = $request->hasFile('input_img')) {
$file = array();
$fileName = $file->getClientOriginalName() ;
$destinationPath = public_path().'/images' ;
$file->move($destinationPath,$fileName);
$UserImage->userImage = $fileName ;
$UserImage = UserImage::create(['file' => $request->file('input_img')]);
$UserImage->user_infos()->associate($user_info);
}
$UserImage->save() ;
return redirect('/home');
}
HomeController(this is where I print out my information)
public function getInfo($id) {
$data = personal_info::where('id',$id)->get();
$data3=UserImage::where('user_id',$id)->get();
return view('test',compact('data','data3'));
blade.php (how I show the image in view)
#foreach ($data3 as $object9)
<img width="100" height="100" src="{!! $object9->signature !!}">
#endforeach
UserImage model(in table I used binary format to store in DB)
class UserImage extends Eloquent
{
protected $fillable = array('userImage','user_id');
public function user_infos() {
return $this->belongsTo('App\user_info', 'user_id', 'id');
}
class user_info extends Eloquent
{
protected $fillable = array('Email', 'Name');
protected $table = user_infos';
protected $primaryKey = 'id';
public function UserImages() {
return $this->hasOne('App\UserImage','user_id');
}
}
create1.blade.php(this is how I upload the image)
<form class="form-horizontal" method="post" action="{{ url('/userUpload')}}" enctype="multipart/form-data">
{{ csrf_field() }}
<div class="form-group">
<label for="imageInput" class="control-label col-sm-3">Upload Image</label>
<div class="col-sm-9">
<input data-preview="#preview" name="input_img" type="file" id="imageInput">
<img class="col-sm-6" id="preview" src="" ></img>
</div>
</div>
<div class="form-group">
<div class="col-md-6-offset-2">
<input type="submit" class="btn btn-primary" value="Save">
</div>
</div>
</form>
I think you have a problem inside store1() method. You sould not re-declare $file.
if($file = $request->hasFile('input_img')) {
$file = array();
$fileName = $file->getClientOriginalName();
Instead get the file using the file() method:
if($request->hasFile('input_img')) {
$file = $request->file('input_img');
$fileName = $file->getClientOriginalName();
See more on the Laravel's requests documentation.
Read through your logic in the store1 method again... You are setting the $file variable to an empty array and then trying to call the getClientOriginalName() method on it:
$file = array();
$fileName = $file->getClientOriginalName();
i use this in laravel 9
$allFile =count($request->files);
for($i=0; $i<$allFile; $i++){
dd($request->files[$i].getClientOriginalName());
}

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