Edit Image of Post With ploymorphic relation - php

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.

Related

laravel Can't delete old image when uploaded new image

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

laravel 8 api : delete file from folder when updating post

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

Looking for Laravel php developer to resolve updating function with image uploading its not working

It's my update function and it's not showing image when I echo $fileName. It's not working like it was I want to make it with the condition if there is any image then update that image otherwise leave that I tried many times but it's not working.
public function update(Request $request, Header $header)
{
if($request->hasFile('headerimg')){
$fileName = $request->file('headerimg')->getClientOriginalName();
$request->file('headerimg')->move('uploads/header',$fileName);
}
$header->title = $request->title;
$header->discription = $request->discription;
$header->keywords = $request->keywords;
$header->headerimg = $fileName;
$header->h2 = $request->h2;
$header->breadcumb = $request->breadcumb;
$header->category = $request->category;
$header->save();
return redirect()->route('dashboard.headers.index')->with('success', 'Packages Edited Successfully');
}
I guess that your problem is in your view.
Maybe you forget to use enctype="multipart/form-data" or your input name does not match with mapped controller variable.
For find the exact problem use dd($request) and dd($request->file('headerimg')) and see can you get request correct or not.
I use this code edit image and if image was not selected the old image will remain same without any error.
public function update(Request $request, Header $header)
{
$file = $request->headerimg;
$id = $request->id;
if($file == ''){
$arr['header'] = Header::select()->where($id);
$fileName = $header['headerimg'];
}
else{
$fileName = $request->file('headerimg')->getClientOriginalName();
$request->file('headerimg')->move('uploads/header',$fileName);
}
$header->title = $request->title;
$header->discription = $request->discription;
$header->keywords = $request->keywords;
$header->headerimg = $fileName;
$header->h2 = $request->h2;
$header->breadcumb = $request->breadcumb;
$header->category = $request->category;
$header->save();
return redirect()->route('dashboard.headers.index')->with('success', 'Page Edited Successfully');
}

Laravel socialite Save avatar

everybody, I need to Save image name in the avatar column in the database
and save the image in public/Storage/users My Code Here Save image link in the database any help, please.
public function handleProviderCallback($service)
{
$user = Socialite::driver($service)->user();
$FindUser = User::where('email',$user->getEmail())->first();
if($FindUser){
Auth::login($FindUser);
}
else{
$NewUser = new User;
$NewUser->email = $user->getEmail();
$NewUser->name = $user->getName();
$NewUser->avatar = $user->getAvatar();
$NewUser->password = bcrypt(123456);
$NewUser->save();
Auth::login($NewUser);
}
return redirect('/');
}
Simply fetch the data using file_get_contents function and process the retrieved data.
use File;
create a helper method to get the avatar
function getSocialAvatar($file, $path){
$fileContents = file_get_contents($file);
return File::put(public_path() . $path . $user->getId() . ".jpg", $fileContents);
}
replace $user->getAvatar()
with the helper method
getSocialAvatar($user->getAvatar(), 'path')

How to upload and save multiple images in database with laravel 5.4?

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

Categories