Search code examples
laravellaravel-8laravel-storage

Get correct URL for uploaded files


I have a function in my platform for letting users upload their own icon images. Once they've uploaded them I save them using $request->icon->store('public/icons') and simply save the returned path, something like "public/icons/xa6y2am3e4cOdqQuLpvEhFSXDKwFMDOgggS2i67l.png".

I'm not really clear though on what's the correct way to show the icons. The URL for showing the icon in the above example is "/storage/icons/xa6y2am3e4cOdqQuLpvEhFSXDKwFMDOgggS2i67l.png", thus I need to replace "public" in the path with "storage", which makes me think I've done something wrong somewhere (I see no reason why the store() method should provide me with a path that's not correct).

I have done my symlinks as described in the documentation. Using the local storage. What am I missing?


Solution

  • This is how I handle my storage in one of my apps that includes blogs:

    $storedImageName = $request->file('main_image')->store('blog_images', 'public');
    

    The store method actually returns the stored file name along with the path. Here, I specify that my disk is public and that the folder inside public is blog_images. I store the result of that in $storedImageName.

    Now, to save it in the database, I do not actually save the whole path, I save ONLY the image name. This is because, you may want to update your directory name in the future, or move it to another location, etc. You can get that like this:

    $onlyImageName = basename($storedImageName);
    

    basename() is PHP's function, has nothing to do with Laravel.

    This way, I can render my images in my blade files like this:

    <img ... src="{{ asset('/storage/blog_images/' . $blog->main_image) }}" />
    

    asset() helper will provide you with path to your public directory, and then you just need to specify the rest of the path to your image.