Skip to content
Advertisement

Foreach image uploaded in a Node Content : get the url

I’m beginning with Drupal 8 and I want to get the url of the photos in the content I create to display them.

The context is: a photograph upload pictures for a customer. This customer can see it on a page. To get this data in common I created a content for my shooting with an id.
What i did is:

$photos = $shooting->field_shooting_photos->target_id;
This allow me to get the id of every pictures uploaded. Now I want to do a foreach on $photos in my .module that will return every url in an array. Then I will use this array in my Twig and do a foreach on it too to return every photos.
I just can’t figure out how to do, I think I will have to use something like that

$path = $photo_id->getFileUri();
but I can’t figure out the syntax to get it into an array. Thank you for your help!

Advertisement

Answer

If you only have a fid, you need to load the file.

use DrupalfileEntityFile;

$fid = 123; // Your fid   
$file = File::load($fid);

From there, you can use the getFileUri method to get the URI. If you want to get the complete URL, you can use the file_create_url function.

$uri = $file->getFileUri();
// You get : public://directory/file.jpg
$url = file_create_url($uri);
// You get : http://mywebsite.com/sites/default/files/directory/file.jpg
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement