lundi 30 juillet 2018

Retrieving media upload in controller from array dynamically

I am using Laravel 5.1 and I am using Illuminate\Http\Request instance for accessing sent file requests, but I can't seem to find the correct way to access the media element. I can access all other values in the object.

Here is the JSON data format I am using:

{"_method":"PUT",
"topic":"1 test",
"description":"1 test",
"media_description":"1 test",
"old_parts":
  {"part-1":
    {"sub_header":"test 2",
     "text_field":"test 2 ",
     "article_id":"18",
     "media":{}},
  "part-2":
    {"sub_header":"test 3 ",
     "text_field":"test 3",
     "article_id":"18",
     "media":{}}
  },
"published":"1",
"media":{}
}

I access media in controller using two foreach loops, one loop is for database collection and other is for form content. I can use following method for accessing media elements.

if ($file = $request->file('media-' . $running_number)) {...} 

But it decreases readability by huge amount as I should name the fields f.e. as media-1, media-2, ... and not access them using foreach loop like I do with everything else.

So is there a way to access file with foreach loop variable?

f.e. something like this

foreach($input['old_parts'] as $old_part) { 

  if ($old_part->hasFile('media')) { ... }

}

If I use the lines I typed the function returns a FatalThrowableError : Call to a member function hasFile() on array.

Or should I just use something like

$request->file('old_parts[part-'.$x.'][media]');

To access the file input and use custom variable to count the index? The problem is just that I can't figure out how to go inside multiple levels in JSON using file, as either old_parts['..']['..'] and old_parts['part-1']->media don't seem to return anything (return null).



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire