skip to Main Content

this code is working but is there a better way for it to make it shorter


        if ($request->has('images')) {
            $images = [];
            foreach ($data['images'] as $image) {
                $images[] = UploadImage::uploadImageToStorage($image, 'Feeds/store/' . $data['store_id']);
            }
            $data['images'] = $images;
        }

2

Answers


  1. I think it is must such. But i cannot check it. Please check it yourself.

    
    $images = collect($data['images']??[])->function($image) use($data){
        return UploadImage::uploadImageToStorage($image, 'Feeds/store/' . $data['store_id']);
    });
    
    
    
    
    Login or Signup to reply.
  2. You may use array_map to get this done.

    $data['images'] = array_map(
      fn($image) => UploadImage::uploadImageToStorage($image, 'Feeds/store/' . $data['store_id']),
      $request->input('images', []) // if "images" cannot be found or empty an array (empty) will be returned
    );
    

    Laravel‘s IlluminateHttpRequest::input($key = null, $default = null) accepts a second argument that will be returned in case the $key cannot be found in the request values. In the above code, if images is not found or empty, an array will be returned.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search