Multiple images deleted from database but not from disc Laravel 7 - php

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.

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

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

Upload multiple images into database using laravel 5.7

i want to upload multiple images and store them into database, but i got an error like this :
file_get_contents() expects parameter 1 to be a valid path, array given
This is my controller :
public function fileMultiple(Request $request) {
$this->validate($request, [
'filename.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048'
]);
if($request->hasfile('filename'))
{
foreach($request->file('filename') as $image)
{
$name=$image->getClientOriginalName();
$image_encod = base64_encode(file_get_contents($request->file('filename')));
$destinationPath = public_path('/images');
$image->move($destinationPath, $name);
$data = new Image();
$data->image_name = $image_encod;
$data->save();
}
}
return back()->with('success', 'Your images has been successfully');
}
how to fix it, the image must encode using base64
You can simply change a little bit in foreach loop and use the $key by following:
foreach($request->file('filename') as $key => $image)
{
$name=$image->getClientOriginalName();
$image_encod = base64_encode(file_get_contents($request->file('filename')[$key]));
$destinationPath = public_path('/images');
$image->move($destinationPath, $name);
$data = new Image();
$data->image_name = $image_encod;
$data->save();
}
The problem is that you're sending the array value.
The following code:
$image_encod = base64_encode(file_get_contents($request->file('filename')));
should be changed into:
$image_encod = base64_encode(file_get_contents($image));
<?php
public function fileMultiple(Request $request) {
$this->validate($request, [
'filename.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048'
]);
if(is_array($request->filename) && count($request->filename) > 0){
foreach ($request->filename as $key => $file) {
if($request->hasFile('filename.' . $key)){
$file = $request->file('filename.' . $key);
if($file->store(public_path('/images')))
{
$data = new Image();
$data->image_name = $image_encod;
$data->save();
return back()->with('success', 'Your images has been successfully');
}
else{
throw new \Exception('Unable to save image.');
}
}
}
}
return back()->with('error', 'Unable to save image.');
}

Add a limit to users creating a item

I am using laravel for a project i am making.
So i want that users can only create 30 products, and if they have more then 30 products, they cant create more products until they have removed some. What do i have to add in my code so that they cant add more products.
My Product controller
public function store(Request $request)
{
//check if user has more then 30 products
$product = Product::create($request->all());
$productPhotos = [];
$photos = $request->post('photo');
if (count($photos) <= 5) {
foreach (range(1, $photos) as $i) {
foreach ($photos as $imageData) {
$bcheck = explode(';', $imageData);
if (count($bcheck) > 1) {
list($type, $imageData) = explode(';', $imageData);
list(, $extension) = explode('/', $type);
list(, $imageData) = explode(',', $imageData);
$fileName = uniqid() . '.' . $extension;
$imageData = base64_decode($imageData);
Storage::put("public/products/$fileName", $imageData);
$imagePath = ('storage/products/' . $fileName);
$productPhotos[] = ProductPhoto::create([
'product_id' => $product->id,
'path' => $imagePath
]);
}
}
}
} else {
return response()->json("You cant add any photo's to your product", 400);
}
return response()->json([$product, $productPhotos], 201);
}
if i need to send some more code, let me know.
Thx in advance.
FINAL CODE:
$totalProduct = Product::where('supplier_id', $request->user()->Supplier->id)->count();
if ($totalProduct < 30){
$product = Product::create($request->all());
$productPhotos = [];
$photos = $request->post('photo');
if (count($photos)) {
foreach ($photos as $i => $imageData) {
if ($i >= 5) {
continue;
}
$bcheck = explode(';', $imageData);
if (count($bcheck) > 1) {
list($type, $imageData) = explode(';', $imageData);
list(, $extension) = explode('/', $type);
list(, $imageData) = explode(',', $imageData);
$fileName = uniqid() . '.' . $extension;
$imageData = base64_decode($imageData);
Storage::put("public/products/$fileName", $imageData);
$imagePath = ('storage/products/' . $fileName);
$productPhotos[] = ProductPhoto::create([
'product_id' => $product->id,
'path' => $imagePath
]);
}
}
}
return response()->json([$product, $productPhotos], 201);
} else{
return response()->json("you have to much products", 201);
}
}
User Model
public function projects()
{
return $this->hasMany('App\Project', 'id', 'user_id');
}
Project Model
public function users()
{
return $this->belongsTo('App\User', 'user_id', 'id');
}
Controller to Add projects
public function store(Request $request)
{
$totalCreatedProjects = $request->user()->products->count();
if ($totalCreatedProjects < 30) {
`Your code to add projects here`
}
`Your code to alert maximum projects achieved here`
}
This example assumed:
1. Your users are authenticated;
2. You created a database relationship 1 to many between Projects and Users;
Notes: When you compare to the amount of projects that exist and the number you wish to hold the creation instead of proceeding, this should be a service.
The number should be a constant with a proper semantic so other developers understand what you are trying to achieve
You can use this:
public function store(Request $request)
{
if($request->user()->products->count() < 30) {
//Add product
...
}else{
return redirect()->back();
}
}
public function store(Request $request)
{
//check if user has more then 29 products
if ($request->user()->products->count() >= 30) {
return response()->json("You cant add more then 30 products", 400);
}
// Your code...
In User Model Add
public function canAddNewProduct()
{
return $this->products->count() < 30;
}
In Controller
Auth::guard('web')->user()->canAddNewProduct()
Better way of doing is make a new middleware and use
return Auth::guard('web')->user()->canAddNewProduct() ? true : false
to protect the routes

Categories