how to update the image? - php

I want to edit the picture, but it doesn't work. What is the syntax for editing a picture?
I tried the following in the controller:
public function edit($id)
{
$makan = Gambar::find($id);
return view('edit_upload',['makan'=>$makan]);
}
public function prosesedit($id, Request $request)
{
$makan = Gambar::find($id);
$makan->nama_makanan = $request->input('makanan');
if($request->hasfile('image'))
{
$file = $request->file('file');
$nama_file = time()."_".$file->getClientOriginalName();
$tujuan_upload = 'image_file';
$file->move($tujuan_upload,$nama_file);
}
$makan->save();
return redirect(route('makan'));
}

Please Try this
public function prosesedit($id, Request $request)
{
$makan = Gambar::find($id);
$nama_file=$makan->file;
if($request->hasfile('image'))
{
$file = $request->file('file');
$nama_file = time()."_".$file->getClientOriginalName();
$tujuan_upload = 'image_file';
$file->move($tujuan_upload,$nama_file);
}
$makan->update([
'file'=>$nama_file
]);
return redirect(route('makan'));
}

Related

Replace image when update in Laravel 8 [duplicate]

This question already has an answer here:
Fetch image variable and display on input file
(1 answer)
Closed 11 months ago.
Both function are same and the store function are running perfectly but update function have some errors
public function store(Request $request)
{
$employee = new Employee;
$employee->phone = $request->emp_num;
$employee->name = $request->emp_name;
$employee->email = $request->emp_email;
$employee->address = $request->emp_add;
if ($request->has('emp_image')) {
$image = $request->file('emp_image');
$filename = $image->getClientOriginalName();
$savePath = env('UPLOAD_PATH');
$image->move($savePath, $filename);
$employee->image = $request->file('emp_image');
}
$employee->save();
return redirect()->route('employee.index')
->with('success','Employee has been created successfully.');
}
public function update(Request $request, employee $employee)
{
$employee->name = $request->emp_name;
$employee->email = $request->emp_email;
$employee->phone = $request->emp_num;
$employee->address = $request->emp_add;
if ($request->has('emp_img')) {
$image = $request->file('emp_img');
$filename = $image->getClientOriginalName();
$savePath = env('UPLOAD_PATH');
$image->move($savePath, $filename);
$employee->image = $request->file('emp_img');
}
$employee->update();
return "Updated";
return redirect()->route('employee.index')
->with('success', $request->emp_name.' Employee data has been Updated successfully.');
}
The error
Call to a member function getClientOriginalName() on null
To store data with image
public function store(Request $request)
{
$category = new Category();
$imageName = time().'.'.$request->image->extension();
$imageName = $request->file('image')
->storeAs('images/category_photo', $imageName, 'public');
$category->name = $request->name;
$category->image = $imageName;
$category->save();
if ($category) {
return redirect()->route('category.index')
->with('success', 'Category Added Successfully');
}
}
To edit data with images and delete the existing image
public function update(Request $request, Category $category)
{
$category->name = $request->name;
if ($request->file('image')) {
$imageName = time().'.'.$request->image->extension();
Storage::delete('public/'.$category->image);
$category->image = $request->file('image')
->storeAs('images/category_photo', $imageName, 'public');
}
$save = $category->save();
if ($save) {
return redirect()->route('category.index')
->with('success', 'Category Updated Successfully');
}
}

How to Delete Images from a folder in Public after update of the image in Laravel 8

I tried to update a form including a file(image) and to have the old image deleted. The update works fine but the old image is unable to delete. I tried this code but the image is not deleted. Please, help me. Thanks in advance.
public function update(Request $request, $id)
{
$slug = SlugService::createSlug(Category::class, 'slug', $request->title);
$request->validate([
'title'=>'required',
'category_image'=>'image'
]);
if ($request->hasFile('category_image')) {
$image = $request->file('category_image');
$newImageName = uniqid().'-'.$request->title.'.'.$image->getClientOriginalExtension();
$location = public_path('/categoryImage');
$OldImage = public_path('categoryImage/'.$request->category_image);
$image->move($location, $newImageName);
Storage::delete($OldImage);
}else {
$newImageName = $request->category_image;
}
Category::where('id', $id)->update([
'slug'=>$slug,
'title'=>$request->input('title'),
'details'=>$request->input('details'),
'category_image'=>$newImageName
]);
return redirect('category')->with('success', 'Category Successfully Updated');
}
public function update(Request $request, $id)
{
...
$category = Category::find($id); #new
if ($request->hasFile('category_image')) {
$image = $request->file('category_image');
$newImageName = uniqid().'-'.$request->title.'.'.$image->getClientOriginalExtension();
$location = public_path('/categoryImage');
$OldImage = public_path('categoryImage/'.$category->category_image); #new
$image->move($location, $newImageName);
unlink($OldImage); #new
}else {
$newImageName = $request->category_image;
}
#you can simplify this as
$category->slug = $slug;
$category->title = $request->title;
$category->details = $request->details;
$category->category_image = $newImageName;
$category->save()
return redirect('category')->with('success', 'Category Successfully Updated');
}
You can delete old image like this , if image is not in root of your storage insert your file location inside storage before image name.
unlink(storage_path('/location_inside_storage/'.$OldImage));

Multiple images deleted from database but not from disc Laravel 7

I am working with Laravel 7 trying to delete multiple images from my app. When I hit the delete button, the images are removed successfully from the show.blade.php as well as from the database. However, they are still in my storage on my local disk. I am storing my images in storage/app/public/upload as well as the symlink pointing to storage/upload in the public directory under app. I have tried a variety of ways to get it to delete but nothing has been fruitful. I have my one to many relationships set up in my models which I will show below. I need this to work under three circumstances such as if there is no image, one image or many images. I am using Laravel Resources for my routing and so my TaskController.php only has one destroy method.
Here is the code I have so far:
Models -
Image.php (relevant functions only - Storage and Task classes imported at top)
public function task()
{
return $this->belongsTo('App\Task', 'task_id');
// return $this->belongsTo(Task::class);
}
public static function boot()
{
parent::boot();
self::deleting(function ($images) {
Storage::delete(Storage::path($images['name']));
});
}
Task.php (relevant code only - Storage, File and Image classes imported at top)
public function images()
{
// return $this->hasMany('App\Image');
return $this->hasMany(Image::class);
}
public static function boot()
{
parent::boot();
self::deleting(function ($task) {
foreach ($task->images ?: [] as $image) {
$image->delete();
}
});
}
Controller
TasksController.php (store, show, update and destroy)
public function store(Request $request)
{
$this->validate($request, [
'task_name' => 'required',
'task_description' => 'required',
]);
// Create Task
$user = Auth::user();
$task = new Task();
$data = $request->all();
$task->user_id = $user->id;
$task = $user->task()->create($data);
if ($request->hasFile('images')) {
$files = $request->file('images');
foreach ($files ?: [] as $file) {
$name = time() . '-' . $file->getClientOriginalName();
$name = str_replace(' ', '-', $name);
$file->storeAs('public/upload', $name);
$task->images()->create(['name' => $name]);
$images = new Image;
$images->name = $name;
}
}
$task->task_name = $request->input('task_name');
$task->task_description = $request->input('task_description');
$task->task_priority = $request->input('task_priority');
$task->task_assigned_by = $request->input('task_assigned_by');
$task->task_assigned_to = $request->input('task_assigned_to');
$task->task_to_be_completed_date = $request->input('task_to_be_completed_date');
$task->task_notes = $request->input('task_notes');
$task->task_status = $request->task_status;
$task->save();
return redirect('/home')->with('success', 'Task Created');
}
public function update(Request $request, $id)
{
$this->validate($request, [
'task_name' => 'required',
'task_description' => 'required',
]);
$task = Task::find($id);
$task->task_name = $request->input('task_name');
$task->task_description = $request->input('task_description');
$task->task_priority = $request->input('task_priority');
$task->task_assigned_by = $request->input('task_assigned_by');
$task->task_assigned_to = $request->input('task_assigned_to');
$task->task_to_be_completed_date = $request->input('task_to_be_completed_date');
$task->task_notes = $request->input('task_notes');
$task->task_status = $request->input('task_status');
if ($request->hasFile('images')) {
$files = $request->file('images');
foreach ($files ?: [] as $file) {
$name = time() . '-' . $file->getClientOriginalName();
$name = str_replace(' ', '-', $name);
$file->storeAs('public/upload', $name);
$task->images()->create(['name' => $name]);
$images = new Image;
$images->name = $name;
}
}
$task->save();
return redirect('/home')->with('success', 'Task Updated');
}
public function show($id)
{
$task = Task::find($id);
return view('tasks.show')->with('task', $task);
}
public function destroy($id)
{
$task = Task::findOrFail($id);
$images = Image::find($id);
$images = explode(',', $images['name']);
foreach ($images as $image) {
// $path = 'storage/app/public/upload/' . $image;
if (file_exists('../storage/app/public/upload/' . json_decode($image, true)['name'])) {
// print_r('file found');
// unlink('../storage/app/public/upload/' . base64_decode($image, true)['name']);
// dd('../storage/app/public/upload/' . json_decode($image, true)['name']);
// File::delete('../storage/app/public/upload/' . json_decode($image, true)['name']);
dd('../storage/app/public/upload/' . $task['image']);
File::delete('../storage/app/public/upload/' . json_decode($image, true)['name'] . $task['images']);
} else {
print_r('no sirve ' . __DIR__ . ' ' . $image . var_dump($image));
}
// dd($path);
// if (File::exists($path)) {
// File::delete($path);
// }
}
// $task->delete();
return redirect('home')->with('success', 'Task Deleted');
}
I have left some commented code included so you can see what I have tried. If I am missing anything, please let me know and I will edit my question.
Thank you in advance for your help. I have been stuck on this for a week.
EDIT
I have changed my destroy function. It still does not delete the files from the disk. Here is the function:
public function destroy($id)
{
// $task = Task::findOrFail($id);
$task = Task::with('images')->findOrFail($id);
// $images = Image::find($id);
// $images = $task->images($id)->get();
foreach ($task->images as $image) {
// dd(storage_path('app/public/upload/' . $image['name']));
Storage::delete(storage_path('app/public/upload/' . $image->name));
}
$task->images()->delete();
$task->delete();
return redirect('home')->with('success', 'Task Deleted');
}
I ended up calling the public folder for the delete function using Storage::disk('public')->delete('upload/' . $image->name);
That in the end helped me to delete the files from my disk. I hope this helps anyone who faces the same issue. Thank you Alzafan Christian for your help in this. You led me in the right direction.

Problem with CRUD(update) Upload File "call to a member function getClientOriginalName() on null"

I want to Update an image using Laravel storage file system in my admin data. However, there's an error when I attempt to upload an image
Iam using Laravel 5.7
Here is my create, the create is success
public function store(Request $request)
{
//
$product = new \App\Product;
$product->product_name = $request->get('product_name');
$product->desc = $request->get('desc');
$product->stock = $request->get('stock');
$product->price = $request->get('price');
$product->category = $request->get('category');
$img = $request->file('img');
$new_name = rand() . '.' . $img->getClientOriginalExtension();
$img->move(public_path('img'), $new_name);
$product->img = $new_name;
$product->save();
return redirect('admin')->with('success', 'Data Produk telah ditambahkan');
}
Here is my update
public function update(Request $request, $id)
{
//
$product = $request->all();
$product= \App\Product::find($id);
$new_name = $request->file('img')->getClientOriginalName();
$destinationPath = 'img/';
$proses = $request->file('img')->move($destinationPath, $new_name);
if($request->hasFile('img'))
{
$product = array(
'product_name' => $product['product_name'],
'desc'=> $product['desc'],
'stock'=> $product['stock'],
'price'=> $product['price'],
'category'=> $product['category'],
'img' => $new_name,
);
$product->save() ;
return redirect('admin')->with('success', 'Data Produk telah ditambahkan');
}
}
Call to a member function getClientOriginalName() on null
I think there is no image file attach while updating. You can use my code as reference.
Don't forget to check for the input field in your update field.
First check if there is image file or not. Then, go for getting name, extension and other staff.
public function update($id, Request $request)
{
$input = $request->all();
$product= \App\Product::find($id);
if (empty($product)) {
Flash::error('product not found');
return redirect(route('products.index'));
}
if ($request->hasFile('product_img')) {
$fileNameWithExt = $request->file('product_img')->getClientOriginalName();
$filename = pathinfo($fileNameWithExt, PATHINFO_FILENAME);
$extension = $request->file('product_img')->getClientOriginalExtension();
$new_product_img = $filename . '_' . time() . '.' . $extension;
$path = $request->file('product_img')->move('images/products', $new_product_img);
Storage::delete('products/'.$product->product_img);
$input['product_img']= $new_product_img;
}
$product= $this->productRepository->update($input, $id);
Flash::success('product updated successfully.');
return redirect(route('products.index'));
}

Laravel : Update field when value is exist

I have some problem with updating file. I have a form with the following attributes :
title
text
pdf file
The problem is the update operation will save the pdf file as the following value :
with file : ["example.pdf"]
no file : [""]
It will include [""] to the pdf file value when updated.
I want the pdf file updated to a new file when a new file is selected, old file remained when there is no new file selected and null value to file when there is no file, to begin with.
Here is the update controller.
public function update()
{
if (Auth::check()) {
$user_id = Auth::user()->id;
$main_id = Input::get('edit_id');
$announcements = Announcement::find($main_id);
$getFile = Input::file('new_brochure');
$rules = array(
'title' => 'required',
'text' => 'required',
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
return back()->withInput()
->withErrors($validator)
->withInput();
}
if ($getFile) {
$file = array('new_brochure' => Input::file('new_brochure'));
$destinationPath = 'img/brochures/announcements'; // upload path
$extension = Input::file('new_brochure')->getClientOriginalExtension();
$fileName = rand(11111,99999).'.'.$extension; // renaming image
Input::file('new_brochure')->move($destinationPath, $fileName);
$announcements->brochure = $fileName;
}
$old = Announcement::where('id',$main_id)->pluck('brochure');
if (empty($old)) {
$announcements->brochure = null;
}
else {
$announcements->brochure = $old;
}
$announcements->title = (Input:: get('title'));
$announcements->from = (Input:: get('from'));
$announcements->to = (Input:: get('to'));
$announcements->text = (Input:: get('text'));
$announcements->is_active = '1';
$announcements->created_by = $user_id;
$announcements->updated_by = $user_id;
$current_date = date("Y-m-d H:i:s");
$announcements->created_at = $current_date.".000";
if ($announcements->save()){
$this->request->session()->flash('alert-success', 'Updated successfully!');
}
else{
$this->request->session()->flash('alert-warning', 'Could not update!');
}
return redirect()->route('Announcements_view');
}
}
What am I doing wrong in this code? Please help me. Thank you.
Change this:
$old = Announcement::where('id',$main_id)->pluck('brochure');
To:
$old = Announcement::where('id',$main_id)->value('brochure');
The thing is pluck() will return a collection of brochure, not a string. And value() will return a string or null.
public function update()
{
if (Auth::check()) {
$user_id = Auth::user()->id;
$main_id = Input::get('edit_id');
$announcements = Announcement::find($main_id);
$getFile = Input::file('new_brochure');
$rules = array(
'title' => 'required',
'text' => 'required',
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
return back()->withInput()
->withErrors($validator)
->withInput();
}
if (!empty(Input::file('new_brochure'))) {
$file = array('new_brochure' => Input::file('new_brochure'));
$destinationPath = 'img/brochures/announcements'; // upload path
$extension = Input::file('new_brochure')->getClientOriginalExtension();
$fileName = rand(11111,99999).'.'.$extension; // renaming image
Input::file('new_brochure')->move($destinationPath, $fileName);
$announcements->brochure = $fileName;
}
else
$old = Announcement::where('id',$main_id)->value('brochure');
$announcements->brochure = $old;
}
$announcements->title = (Input:: get('title'));
$announcements->from = (Input:: get('from'));
$announcements->to = (Input:: get('to'));
$announcements->text = (Input:: get('text'));
$announcements->is_active = '1';
$announcements->created_by = $user_id;
$announcements->updated_by = $user_id;
$current_date = date("Y-m-d H:i:s");
$announcements->created_at = $current_date.".000";
if ($announcements->save()){
$this->request->session()->flash('alert-success', 'Updated successfully!');
}
else{
$this->request->session()->flash('alert-warning', 'Could not update!');
}
return redirect()->route('Announcements_view');
}
}

Categories