Deleting multiple records in laravel using foreach loop - php

I am trying to delete multiple images using product_id, I am able to delete one image at a time but am figuring out how i can insert a variable like $i=0 to a loop over but it does not work in laravel.
so far this is my code
public function ImageDelete($slider_id)
{
//int $i=0; Had introduced this but doesn't work
$slider = Products::findOrFail($slider_id);
foreach($slider as $product){
$product_images=$slider->images()->get();
$image_path = public_path().'\images2\\'.$product_images[0]->filename;
File::delete($image_path);
//$i++;
}
$slider->delete();
return response()->json(['success'=>'Pics deleted successfully!']);
}

The findOrFail method return only one item. So you cannot iterate over it.
You can use the each method
$product = Products::findOrFail($id);
$images = $product->images()->get();
$images->each(function ($file, $key) {
$filePath = public_path("images2/") . $file->filename;
File::delete($filePath);
});
// Delete the product
$product->delete();

Try this:
public function ImageDelete($slider_id)
{
$product = Products::find($slider_id);
$product_images=$product->images()->get();
foreach($product_images as $product_image){
$image_path = public_path().'\images2\\'.$product_image->filename;
File::delete($image_path);
}
$product->delete();
return response()->json(['success'=>'Pics deleted successfully!']);
}

Related

Laravel 8 not finding "tag" from package "\Conner\Tagging\Taggable;"

The code works perfectly when I want to create a new tag from scratch, but when $skillsQuery->count() > 0 and enters in the if statement. It prints...
Method Illuminate\Database\Eloquent\Collection::tag does not exist.
How can I update tags using this package?
Controller
<?php
public function storeSkills(Request $request)
{
$id = auth()->user()->id;
$skillsQuery = Skill::where('created_by', $id)->get();
// If skill exists
if ($skillsQuery->count() > 0) {
$input = $request->all();
$tags = explode(", ", $input['name']);
// $skill = Skill::create($input);
$skillsQuery->tag($tags);
$skillsQuery->created_by = $id;
if ($skillsQuery->save()) {
return redirect()->route('profile')->with('success', 'Skills updated successfully');
} else {
return redirect()->route('profile')->with('error', 'Error updated your Skills!');
}
} else {
$input = $request->all();
$tags = explode(", ", $input['name']);
$skill = Skill::create($input);
$skill->tag($tags);
$skill->created_by = $id;
if ($skill->save())
return redirect()->route('profile')->with('success', 'Skills stored successfully');
else {
return redirect()->route('profile')->with('error', 'Error storing your Skills!');
}
}
}
The result of calling ->get() on a Illuminate\Database\Query is that you will receive an instance of a Illuminate\Database\Collection, which does not contain a ->tag() method. Even if it was a query (by removing ->get()) this still would not work, as you can't call a relationship method off of a collection.
If instead you loop over the skillsQuery then you will receive an instance of a Model object which then allows you to access functions and/or relationships off of it:
$skillsQuery->each(function ($skill) use ($tags) {
$skill->tag($tags); // or perhaps ->retag($tags); here
});

Update multiple ids against single id (Laravel)

I want to update multiple Departments against one unit. I tried this method, but it's not correct.
How can I update multiple departments ids?
Form:
Request:
Controller Function:
$pre_data = UnitDepartment::where('unit_id', $request->id)->get();
if ($pre_data) {
foreach ($pre_data as $value) {
$value->delete();
}
$department = $request->department_id;
foreach ($department as $value) {
$unitDepart = new UnitDepartment();
$unitDepart->unit_id = $request->id;
$unitDepart->department_id = $value;
$unitDepart->save();
}
}
table:
I found that is the table related to departments and units.
So you can build the relationship many-to-many between them,
Create the relationship in your models,
In Unit model:
public function departments()
{
return $this->belongsToMany('App\Unit','unit_department','unit_id','department_id');
}
In Department Model:
public function units()
{
return $this->belongsToMany('App\Department','unit_department','department_id','unit_id');
}
Attach the new relationship, simply use:
Unit::find($request->unit_id)->departments()
->sync($request->department_id);
Unfortunately, you cannot use softDelete on sync().
And I don't think you need to soft delete with unit_departments. As a pivot then it should be irrelevant if it is deleted or not.
And if user update the relationship on the frequent, this table will grow fast.
If you really need to soft-delete, you can write it like this:
$department_ids = $request->department_id;
$unit_id = $request->unit_id
// soft delete the unit_departments not in request:
UnitDepartment::where('unit_id', $unit_id)->whereNotIn('department_id', $department_ids)->delete();
// insert the new department_id+unit_id relationship
$exist_department_ids = UnitDepartment::where('unit_id', $unit_id)->whereIn('department_id', $department_ids)->pluck('department_ids')->all();
$dept_ids = array_diff($exist_department_ids, $department_ids);
$depts = collect($dept_ids)->map(function($dept_id) use ($unit_id) {
return ['department_id' => $dept_id, 'unit_id' => $unit_id];
});
UnitDepartment::insert($depts);
the problem is you're sending unit_id in the request, however using $request->id in the query which is wrong.
Change every occurance of $request->id with $request->unit_id in the controller.
to select pre data correctly
use
$pre_data = UnitDepartment::where('unit_id', $request->id)->first();
i tried this
$unit = UnitDepartment::where('unit_id', $request->unit_id)->get();
foreach ($unit as $item) {
$existDepartment[] = $item->department_id;
}
$newDepartment = $request->department_id;
$result = array_diff($newDepartment, $existDepartment);
if ($result) {
foreach ($result as $item) {
$data = new UnitDepartment();
$data->unit_id = $request->unit_id;
$data->department_id = $item;
$data->save();
}
}

Only one function is working either Delete from DB or Delete from Server

I am trying to Delete Images of a Post, But only one action is performing which I put First. Either Delete from DB or Delete from Folder / Server.
Both Action Works Fine but only One Which i Put First.
Note: I am call this Controller function through Ajax Get Request from Blade/View
public function deletePermanently(){
$id = Input::get('id');
Photo::where('post_id',$id)->delete();
$obj = Post::with(['pictures'])->find($id);
$filePath = public_path().'/upload/';
if(count($obj->pictures) > 0){
foreach($obj->pictures as $photo){
if(file_exists($filePath.$photo->name)){
unlink($filePath.$photo->name);
}
}
}
}
I am expecting Delete from both DB and Folder / Server at once
You were deleting the pictures in the database without taking the pictures I have taken the pictures before the delete action is executed.
Photo::where('post_id',$id)->delete();
$obj = Post::with(['pictures'])->find($id);
I have swapped the order of these lines
$obj = Post::with(['pictures'])->find($id);
Photo::where('post_id',$id)->delete();
Your final code should look like this
public function deletePermanently(){
$id = Input::get('id');
$obj = Post::with(['pictures'])->find($id);
Photo::where('post_id',$id)->delete();
$filePath = public_path().'/upload/';
if(count($obj->pictures) > 0){
foreach($obj->pictures as $photo){
if(file_exists($filePath.$photo->name)){
unlink($filePath.$photo->name);
}
}
}
}
You must delete the image and then delete the record. If you delete the record you can't find the record again to delete the image. So do something like this:
public function deletePermanently(){
$id = Input::get('id');
$obj = Post::with(['pictures'])->find($id);
$filePath = public_path().'/upload/';
if(count($obj->pictures) > 0){
foreach($obj->pictures as $photo){
if(file_exists($filePath.$photo->name)){
unlink($filePath.$photo->name);
}
}
}
Photo::where('post_id',$id)->delete();
}
you can try like this
use Illuminate\Support\Facades\Storage;
Storage::delete('file.jpg');

Laravel - Delete data record from Database

I want to delete record Photo and Photo_list from Database but give me error
This is my Code in Controller
public function deletephoto($id)
{
$product = $this->productRepository->findWithoutFail($id);
Product::select('photo','photo_list')->delete($product->id);
return redirect(route('stores.index'));
}
I don't think you can delete specific data with delete.
Delete is used to remove a row.
You will need to update your table with a request like that :
public function deletephoto($id)
{
$product = $this->productRepository->findWithoutFail($id);
Product::where('id', 100)->update(['photo' => NULL, 'photo_list' => NULL]);
return redirect(route('stores.index'));
}
You can see more here :
https://laravel.com/docs/5.3/eloquent#updates
https://laravel.com/docs/5.3/eloquent#deleting-models
You can try this :
public function deletephoto($id)
{
$product = $this->productRepository->findWithoutFail($id);
if($product){
$product->photo= null;
$product->photo_list= null;
$product->save();
}
return redirect(route('stores.index'));
}
public function deletephoto($id)
{
$product = $this->productRepository->findWithoutFail($id);
Product::Where('id','=',$product->id)->delete();
return redirect(route('stores.index'));
}
Or you can directly do this
Product::find($id)->delete();
Try this
Product::WhereProductId($product->id)->delete();

BadMethodCallException in Macroable.php line 81:Method update does not exist

I an developing a page to create, update, delete and view an event in which there is error while updating the event. There is a event table and a event_collection table. In that event_collection table there is event_id which is id of an event and a collection_id which is from other table collection.
When i create an event, all the data gets stored in event table except the collection one. in the collection table data gets stored in one by one manner like if I check 2 items in collection, it will generate 2 ids with same event_id and 2 collection_ids.
There is problem in update, when i try to update the code, it gives me error as
BadMethodCallException in Macroable.php line 81:
Method update does not exist.
Update method is:
public function update(EventRequest $request, $id)
{
$event = Event::findOrFail($id);
$input = $request->all();
$input['days_of_week'] = serialize(Input::get('days_of_week'));
$query = $event->update($input);
$checkbox_selection = Input::get('agree');
$choosen_checkbox = $id;
$collection_event = EventCollection::where('event_id',$choosen_checkbox)->get();
// return $collection_event;
if (!is_null($checkbox_selection)) {
foreach ($checkbox_selection as $collection) {
// $collection_id = $id;
foreach($collection_event as $k){
// return $k;
if($k->event_id == $choosen_checkbox){
$data = $request->all();
$data['event_id']= $choosen_checkbox;
$data['collection_id'] = $collection;
$collection_event->update($data);
}
}
}
}
My store method is:
public function store(Request $request)
{
$checkbox = Input::get('days_of_week');
$checkbox_selection = Input::get('agree');
// return $checkbox_collection;
$input = $request->all();
$input['days_of_week'] = serialize($checkbox);
$query = Event::create($input);
$event_id = $query->id;
$pro_id = $query->provider_org_id;
/*For the checkbox selection, if they are multiple store each separately*/
if (!is_null($checkbox_selection)) {
foreach ($checkbox_selection as $collection) {
$collection_id = $query->id;
if($collection_id){
$data = $request->all();
$data['event_id']= $collection_id;
$data['collection_id'] = $collection;
$create_collection = EventCollection::create($data);
}
}
}
return view('event.pic_upload',compact('event_id','pro_id'));
}
Store method works properly! Can someone please tell any solution? I am badly stucked in this.
I do not think the 'update' method works on collections.
This line will return a collection
$collection_event = EventCollection::where('event_id',$choosen_checkbox)->get();
You do not want a collection, rather a query. As given in the docs:
`App\Flight::where('active', 1)
->where('destination', 'San Diego')
->update(['delayed' => 1]);`
Try removing the '->get()' from the statement.

Categories