Onyx
Onyx

Reputation: 5772

I have a foreach loop but I need to include information which is in another array in it as well

The code below is used to delete all checked categories in the checkbox, however, I have a hidden input field for each checkbox that contains the file name of the image used as thumbnail and since I don't want to make queries to get the file name, I'm passing it as hidden input.

So $request['categoryFiles'] contains the file name for each $request['categories'], however, I'm not sure how to use that array in the foreach so that I can fill Storage::delete('public/uploads/categories/'.???); with the correct index of the $request['categoryFiles'] array.

The ??? have to be replaced with something like $request['categoryFiles'][0], $request['categoryFiles'][1], etc for as long as the foreach is looping

public function deleteCategories(Request $request){

    if (!Auth::user()->hasRole('Admin')) {
            return redirect()->back();
    } else if (Auth::user()->hasRole('Admin')) {
        $categories = $request['categories'];
        $categoryFiles = $request['categoryFiles'];
        foreach ($categories as $category) {
            Storage::delete('public/uploads/categories/'.???);
            Storage::delete('public/uploads/categories/thumbnails/'.???);
        }
        Category::whereIn('id', $categories)->delete();
        return redirect()->back();
    }

}

Upvotes: 0

Views: 34

Answers (1)

Nigel Ren
Nigel Ren

Reputation: 57121

You can use the key from the categories to match against the other array...

foreach ($categories as $key => $category) {
    Storage::delete('public/uploads/categories/'.$categoryFiles[$key]);
    Storage::delete('public/uploads/categories/thumbnails/'.$categoryFiles[$key]);
}

Upvotes: 2

Related Questions