i have posts tables and i upload images for it , so in update() method in PostController() i want to edit post and images
for editing images , i want to delete last images from folder and database , and replace new images.
so i can delete last images from database but i can't delete them from folder
the controller :
public function update(StorePostRequest $request , $id )
{
$validatedData = $request->all();
if ($request->hasfile('image')) {
$postTitle = $request->title; //post title for folder name and the images inside it
//delete last Images from database for updating images
Image::where('imageable_type' , 'App\Models\Post')->where('imageable_id' , $id)->delete();
$directory =storage_path().'/images/posts/'.$postTitle;
if($directory){
Storage::disk('public')->deleteDirectory('images/posts/.$postTitle');
}
$files = $request->file('image');
foreach ($files as $file) {
$imageName = time().rand(1,10000).'.'.$file->extension();
$postTitle = $request->title; //post title for folder name and the images inside it
$imagePath = public_path(). '/images/posts/'.$postTitle;
$file->move($imagePath, $imageName);
$image = new Image;
$image->image = $imageName;
$image->path = $imagePath;
$images[] = $image; // make an array of uploaded images
}
}
$post = Post::find($id);
$post->category_id = $validatedData['category_id'];
$post->title = $validatedData['title'];
$post->body = $validatedData['body'];
$post->study_time = $validatedData['study_time'];
$post->save();
$post->images()->saveMany($images);
return response()->json([
"success" => true,
"message" => "successfully",
"data" => $post
]);
}
the relation between posts and images is : one to many polymorphic and i taste it with postman
i tried this ways and it doesn't work :
File::delete(public_path('/images/posts/'.$postTitle));
Storage::disk('public')->deleteDirectory($directory);
in addition , when i try
Storage::disk('public')->deleteDirectory('images/posts/');
it works and the posts folder has been deleted , but the problem is from $postTitle
when i use it, doesn't work
you can use this code for delete file
if (!is_dir(public_path('/images/posts/'.$postTitle))) {
mkdir(public_path('/images/posts/'.$postTitle));
}
If you need to delete directory use Storage::disk('public')->deleteDirectory('images/posts');
Related
why my old image can't be deleted when i uploaded new image?
this is my controller where i use to store data and image.
my file image name is stored combination from nama_post_adps and from $imageName where that is query for getClientOriginalName();
public function update(Request $request, Adopsi $adopsi, $id)
{
$getParentJenisHewan = JenisHewan::where("id", $request->jenis_hewan_id)->value("nama_jenis_hewan");
$getParentRasHewan = RasHewan::where("id", $request->ras_hewan_id)->value("nama_ras_hewan");
$imageSize = $request->file('image_post_adps')->getSize();
$imageName = $request->file('image_post_adps')->getClientOriginalName();
$pathstorage = $request->file('image_post_adps')->storeAs('public/post/adopsi',$request->nama_post_adopsi.'-'.$imageName);
$adopsiAttr = $this->validasiRequest();
$adopsiAttr = $request->all();
$adopsiAttr['nama_jenis_hewan'] = $getParentJenisHewan;
$adopsiAttr['nama_ras_hewan'] = $getParentRasHewan;
$adopsiAttr['image_post_adps'] = $imageName;
$adopsiAttr['path-storage'] = $pathstorage;
$adopsiAttr['size'] = $imageSize;
$adopsi = Adopsi::find($id)->update($adopsiAttr);
$delete = Adopsi::find($id);
unlink('app/public/post/adopsi/'.$delete->nama_post_adopsi.'-'.$delete->image_post_adps);
// if ($request->file('image_post_adps')) {
// Storage::disk('public')->delete('/post/adopsi/'.$request->nama_post_adopsi.'-'.$request->image_post_adps);
// }
if($adopsi) {
return redirect()->route('adopsi.index')->with('success','Data '.$request->nama_post_adopsi .' telah mendapatkan update terbaru.');
} else {
return redirect()->route('adopsi.index')->with('error','Data gagal'.$request->nama_post_adopsi .'diupdate');
}
}
method above literally same with my store method .
i've try unlink() but it can't work and show error : unlink('post/adopsi/..') no such file or directory , but field can't be updated. then i decided use Storage::disk('public')->delete , field got update, the image change with new but old still same.
You are doing wrong.
First fetch existing data and check if request has file then delete old one then update it
$delete = Adopsi::find($id);
if ($request->file('image_post_adps')) {
Storage::disk('public')->delete('/post/adopsi/'.$delete->nama_post_adopsi.'-'.$delete->image_post_adps);
}
$adopsi = Adopsi::find($id)->update($adopsiAttr);
I Trying to upload multiple image for my product, and store the names of that images in database as an array.
My code works like this-
$images = $request->file('images');
if (isset($images)) {
foreach($images as $image){
$imagename = $slug.'-'.$currentDate.'-'.uniqid().'.'.$image->getClientOriginalExtension();
if (!file_exists('uploads/product/images')) {
mkdir('uploads/product/images', 0777, true);
}
$image->move('uploads/product/images', $imagename);
$data[] = $imagename;
}
}else{
$data[] = 'default.png';
}
$product = new Product();
$product->images = json_encode($data);
And data stored inside the images field like-
["jeans-2020-08-13-5f352f18b30a4.jpg","jeans-2020-08-13-5f352f18b36a0.jpg","jeans-2020-08-13-5f352f18b3a2c.jpg"]
**And the problem is how can i separate this image name to show images in Laravel Blade? **
OR Suggest me, If there is another way to upload multiple image or multiple value in laravel-6
You need to deserialize the images names and then loop through them:
#foreach(json_decode($product->images) ?? [] as $image)
<img src="uploads/product/images/{{ $image }}">
#endforeach
im trying to upload multiple images with laravel 5.4, actually the process to upload images is done, the question is how to store them in database?
for example when gonna create a slide show of something that has several images that is uploaded, how to group them so the slide show knows those images are in one group?
can you guys help me?
Make sure you go to config/filesystems and turn 'FILESYSTEM_DRIVER' to 'public'
Model to store image paths:
class UserDocuments extends Model
{
//
protected $table = 'user_documents';
public function store($user_id, $document_link, $file_name)
{
$this->user_id = $user_id;
$this->document_link = $document_link;
$this->file_name = $file_name;
$this->save();
}
}
Code in controller to store files ('document' is file input field name)
if ($request->hasFile('document')) {
$link = $request->file('document')->store('documents');
}
$userDocuments->store(request('user_id'), url($link), $link);
To show if the images are in a group, you would have to create a database column called 'group_id' and sort them accordingly.
We have to store images into one records/row by separting commas.
class DocumentController extends Controller
{
public function store(Request $request)
{
$pid = $request->input('pid');
$input = $request->file('files');
$picture = array();
if($request->hasFile('files')) :
foreach ($images as $item):
$extension = $item->getClientOriginalName(); //image extension
$name = time() . '.' .$extension; //image name
$item->move('uploads/documents/', $name); //move to destination
$arr[] = $name; //store image into array
endforeach;
$picture = implode(",", $arr); //Image separated by comma
else:
$picture = '';
endif;
DB::table('document')->insert(array('pid' => $pid,'image' => $picture));
Session::flash('message', 'Multiple Images are uploaded successfully');
return redirect('/multiple-image');
}
}
I need to display the stored images in my view.I've used the below code to store image in db,
$file = Input::file('pic');
$img = Image::make($file);
Response::make($img->encode('jpeg'));
$picture = new Car;
$picture->cartype = Input::get('cartype');
$picture->price = Input::get('price');
$FileName = Input::file('pic')->getClientOriginalName();
$FilePath = public_path('') .'/images/'. $FileName;
$picture->name = $FilePath;
$picture->save();
In my controller( to retrieve image)
public function index()
{
$cars = DB::table('car_category')->get();
return view('category.category',['cars'=>$cars]);
}
How should I retrieve and display the images in view?
If you are storing the image name in the database and uploading it in a directory then you can easily display it by simply fetching the name from database, returning the name to view and append the name to a hard-coded directory address like this -
<img src="/images/{{ $imageVariableName }}">
Let me know if this works.
Hy all,
I need to update the picture of a article, all it's fine for updating post but my question it's how to update the image of this post with my polymorphic relation.
i have a table Images with imageable_id imageable_type path .
in my Post controller update function i have
public function update($id)
{
$inputs = Input::all();
$rules =array(
'name'=>'required|min:5',
'description'=>'required|min:10',
);
$validation = Validator::make($inputs,$rules);
if($validation->fails()){
return Redirect::to('posts/'.Input::get('id').'/edit')->withInput()
->withErrors($validation)
->with('alert_error','Veuillez corriger les érreurs SVP');
}
if(Input::hasFile('mediafile')){
$file = Input::file('mediafile');
$name = date('Ymd') . '-' . $file->getClientOriginalName();
$file = $file->move('img/uploads/', $name);
$path = $file->getRealPath();
//take the path only at the img not totally
$pos = strpos($path,'/img/');
if ($pos !== false) {
$path = substr($path, $pos + 1);
}
$input['file'] = $path;
$post=Post::find(Input::get('id'));
$post->name = e(Input::get('name'));
$post->description = e(Input::get('description'));
$post->category_id = e(Input::get('categories'));
$post->tag_id = e(Input::get('tag'));
$post->rating = e(Input::get('rating'));
$post->content = Input::get('content');
$post->is_online = e(Input::get('online'));
$post->images->path = e(Input::get('mediafile'));
$post->save();
}
}
My model Post
public function images(){
return $this->morphMany('Image','imageable');
}
So i wish update only the path of my image in my table Image when i submit my form to show the new picture of post.
Thank's for help
The morphMany will return a collection of Images, so when you run $post->images->path you're setting the path attribute on the collection not on an image model. If a Post is only meant to have one image, change it to a morphOne or alternatively you will have to identify the image model you wish to update from the collection.