Hi please help me am new to laravel I want to store multiple image paths in
table... With this code am unable to save.
Help me for this..
Here in my View
{{Form::open(array('url'=>'businessdirectory/business', 'files'=>true))}}
{{Form::label('image','Upload Image')}}
<div class="form-group">{{Form::file('image[]',array('multiple'=>true))}}
</div>
{{Form::close()}}
In my Controller
if(Input::file('image'))
{
$image = Input::file('image');
foreach($image as $img) {
$destination = 'images';
$filename = $img->getClientOriginalName();
$path = 'images/'.$filename;
$uploadSuccess = $img->move($destination,$filename);
}
}
else
{
$path='images/default.JPG';
}
$business = new Business();
$business->image = $path;
$business->save();
Related
Hello I am a newbie, I just started creating a project for quiz application.I have repeated code in my store and update
function,how can i reduce the duplication and write a cleaner code, any help will be appreciated
Thanks Nabeel
This is my store method
public function store(Quiz $quiz, QuestionRequest $request)
{
if($request->hasfile('image'))
{
$file=$request->file('image');
//Get File name with the extension
$fileWithExt = $file->getClientOriginalName();
//Get Just File Name
$filename = pathinfo($fileWithExt,PATHINFO_FILENAME);
//Get Just Extension
$extension = $file->getClientOriginalExtension();
//Filename to store
$nameoffile = $filename.'_'.time().'.'.$extension;
//Upload Image
$path = $file->move(public_path('images'),$nameoffile);
//$path = $file->storeAs('app/img/',$nameoffile);
$path = $nameoffile;
}
else
{
$path=null;
}
}
This is my update method
public function update(Quiz $quiz,QuestionRequest $request,Question $question)
{
if(is_null($question->imgpath))
{
if($request->hasfile('image'))
{
$file=$request->file('image');
//Get File name with the extension
$fileWithExt = $file->getClientOriginalName();
//Get Just File Name
$filename = pathinfo($fileWithExt,PATHINFO_FILENAME);
//Get Just Extension
$extension = $file->getClientOriginalExtension();
//Filename to store
$nameoffile = $filename.'_'.time().'.'.$extension;
//Upload Image
$path = $file->move(public_path('images'),$nameoffile);
$path = $nameoffile;
}
else
{
$path=null;
}
}
elseif(!empty($question->imgpath) && $request->hasfile('image'))
{
$file=$request->file('image');
$fileWithExt = $file->getClientOriginalName();
$filename = pathinfo($fileWithExt,PATHINFO_FILENAME);
$extension = $file->getClientOriginalExtension();
$nameoffile = $filename.'_'.time().'.'.$extension;
$path = $file->move(public_path('images'),$nameoffile);
$path = $nameoffile;
}
else
{
$path=$question->imgpath;
}
You can create a new trait or function in your model class and can use that in your controller . Like this
In your Quiz.php just create a new function called fileUpload()
php artisan fileUpload($data)
{
$file=$data;
//Get File name with the extension
$fileWithExt = $file->getClientOriginalName();
//Get Just File Name
$filename = pathinfo($fileWithExt,PATHINFO_FILENAME);
//Get Just Extension
$extension = $file->getClientOriginalExtension();
//Filename to store
$nameoffile = $filename.'_'.time().'.'.$extension;
//Upload Image
$path = $file->move(public_path('images'),$nameoffile);
$path = $nameoffile;
return $path;
}
And in your controller in store() and update() you can just do this
if(is_null($question->imgpath))
{
if($request->hasfile('image'))
{
$path = $quiz->fileUpload($request->file('image'));
}
else
{
$path=null;
}
}
this is still related to my post in here How to remove and unlink multiple images in json format
i can store and delete all multiple images. but i have still problem when update and remove old image. my code still not remove the oldimage when update the new image.
my update controller, i use handlerequest method to store images, where oldImage is variable in database that will be compared with new images. if not same then remove old images.
public function update(Requests\UpdatePostRequest $request, $id)
{
$post = Post::findOrFail($id);
$oldImage = $post->image;
$data = $this->handleRequest($request);
$post->update($data);
if($oldImage != $post->image)
{
foreach (json_decode($post->image, true) as $oldImage) {
$this->removeImage($oldImage);
}
}
if($request->submitbutton =='Publish')
{
Alert::success('Your post was updated successfully')->persistent('Close');
return redirect(route('admins-blogpost.index'));
}
if($request->submitbutton =='Save Draft')
{
Alert::success('Your draft was updated successfully')->persistent('Close');
return redirect(route('admins-blogpost.index'));
}
}
my handlerequest method to store multiple image, this method is working using store method. so this problem not here.
private function handleRequest($request)
{
$data = $request->all();
if($request->hasFile('image'))
{
$images = $request->file('image');
foreach($images as $key=>$image){
$fileName = $image->getClientOriginalName();
$destination = $this->uploadPath;
$successUploaded = $image->move($destination, $fileName);
if($successUploaded)
{
$width = config('cms_blog.image.thumbnail.width');
$height = config('cms_blog.image.thumbnail.height');
$extension = $image->getClientOriginalExtension();
$thumbnail = str_replace(".{$extension}", "_thumb.{$extension}", $fileName);
Image::make($destination . '/' . $fileName)
->resize($width,$height)
->save($destination . '/' . $thumbnail);
$datax[] = $fileName;
}
$data['image'] = json_encode($datax);
}
}
return $data;
}
and delete method
public function removeImage($image)
{
if( ! empty($image))
{
$imagePath = $this->uploadPath . '/' . $image;
$ext = substr(strrchr($image, '.'), 1);
$thumbnail = str_replace(".{$ext}", "_thumb.{$ext}", $image);
$thumbnailPath = $this->uploadPath . '/' . $thumbnail;
if(file_exists($imagePath) ) unlink($imagePath);
if(file_exists($thumbnailPath) ) unlink($thumbnailPath);
}
}
how to fix my problem so i can remove old images when their not same with new image?
In the for loop where you delete the images, I believe you wanted to iterate over $oldImage, not over $post->image:
foreach (json_decode($oldImage, true) as $item) {
$this->removeImage($item);
}
Storing multiple images name on a single column, which is not a good idea. I suggested you create another table post_images or something else.
And create hasMany relation from posts table with post_images table. Then you have lot's of flexibility here. Also, you can create a Polymorphic Relationship to use the same image model with multiple Models.
I am trying to insert in image table but following syntax is showing method save does not exit:BadMethodCallException in Macroable.php line 74:.
Controller:
foreach ($request->file('image') as $i)
{
$image = new image();
$image = $i;
$input['imagename'] = $request->vname.'_'.$user->id.'_'.str_random(2).'.'.$image->getClientOriginalExtension();
$destinationPath = public_path('/images');
//move image to folder
$image->move($destinationPath, $input['imagename']);
$image->title=$input['imagename'];
$image->filepath=$destinationPath;
$image->Vehicle_id=$vehicles->id;
$image->save();
}
Can anyone tell me what am i doing wrong?
This will do the job.
You replaced your model's object with file here $image = $i; therefore no save method is availble for $image.
foreach ($request->file('image') as $file)
{
$image = new image();
$input['imagename'] = $request->vname.'_'.$user->id.'_'.str_random(2).'.'.$file->getClientOriginalExtension();
$destinationPath = public_path('/images');
//move image to folder
$file->move($destinationPath, $input['imagename']);
$image->title=$input['imagename'];
$image->filepath=$destinationPath;
$image->Vehicle_id=$vehicles->id;
$image->save();
}
Hi please help me am new to laravel
I want to store multiple images in table... With this code am unable to save.
Help me for this..
Here in my View
{{Form::open(array('url'=>'businessdirectory/business', 'files'=>true))}}
{{Form::label('image','Upload Image')}}
<div class="form-group">{{Form::file('image[]',array('multiple'=>true))}}
</div>
{{Form::close()}}
In my Controller
if(Input::file('image'))
{
$image = Input::file('image');
foreach($image as $img) {
$destination = 'images';
$filename = $img->getClientOriginalName();
$path = 'images/'.$filename;
$uploadSuccess = $img->move($destination,$filename);
}
}
else
{
$path='images/default.JPG';
}
$business = new Business();
$business->image = $path;
It's not advisable to store images on database. Just save the path of the images instead.
If you really need to store image on db. Make sure you set the column to blob as it need more space. Then, get the image content and type, then save it.
<?php
$image = fopen($image_path, 'rb');
// or
$image = file_get_contents($image_path);
$business = new Business;
$business->image = $image;
$business->imageType = "image/gif"; //
$business->save();
// ...
You need to put below code inside the foreach loop. In every loop you need to insert image path inside a database
$business = new Business();
$business->image = $path;
This is a working code in laravel 5.2.
$files = $request->file('file');
if($request->hasfile('file')){
$destinationPath = 'uploads';
foreach($files as $file){
$image = new Image;
$filename = $file->getClientOriginalName();
$image->name = $filename;
$image->save();
$file->move($destinationPath,$filename);
}
Any best way to do this will be gratefull
what this do is grab the input from a form and save it to the database.
public function update()
{
$file = Input::file('path');
$destinationPath = 'img/';
$filename = $file->getClientOriginalName();
// $extension =$file->getClientOriginalExtension();
$upload_success = Input::file('path')->move($destinationPath, $filename);
$photo = Photo::find($_POST['id']);
$photo->caption = $_POST['caption'];
$photo->path = $destinationPath . $filename;
$photo->save();
if( $upload_success ) {
return Redirect::to('photos/'.$_POST['id'].'/edit')->withInput()->with('success', 'Photo have been updated.');
} else {
return Response::json('error', 400);
}
}
this work just fine but i wonder if there a simplify way to do this like how i can get post data from the form send to update to update the photo information instead of me using the $_POST and get the id from the form parse into the update($id) ect. Thanks
You can use the Input class, instead of accessing the post directly.
I would probably re-write the function a little like this:
public function update()
{
$file = Input::file('path');
$destinationPath = 'img/';
$filename = $file->getClientOriginalName();
if( Input::file('path')->move($destinationPath, $filename) )
{
$photo = Photo::find(Input::get('id'));
$photo->caption = Input::get('caption');
$photo->path = $destinationPath . $filename;
$photo->save();
return Redirect::to('photos/'.$_POST['id'].'/edit')->withInput()->with('success', 'Photo have been updated.');
}
else
{
return Response::json('error', 400);
}
}
The other option is to extract some of this data directly into your Photo model, and do it in there.