Get image from resources folder - Laravel

Viewed 6606

Can I get and display an image in view from a resources folder instead of public folder? If yes, how can I do that?

5 Answers

resources folder should not be used to store images That's not where public, static assets (like images, js, css etc) should be.

Put them inside public/ folder

The resources/assets/ directory is for storing pre-processed assets, so to speak.

For example, if you have 3 different CSS files but want to merge them into one and render that new single file in the browser (to increase page load speed). In this scenario, the 3 CSS files will be put somewhere inside resources/assets/.

These files can then be processed, and the new merged file will go inside public.

Reference:

https://laracasts.com/discuss/channels/laravel/image-assets?page=1

You can make a route specifically for displaying images.

Route::get('/resources/app/uploads/{filename}', function($filename){
    $path = resource_path() . '/app/uploads/' . $filename;

    if(!File::exists($path)) {
        return response()->json(['message' => 'Image not found.'], 404);
    }

    $file = File::get($path);
    $type = File::mimeType($path);

    $response = Response::make($file, 200);
    $response->header("Content-Type", $type);

    return $response;
});

now you can go to localhost/resources/app/uploads/filename.png and it should display the image.
reference How to get image from resources in Laravel?
But again say that resources folder should not be used to store images That's not where public, static assets (like images, js, css etc) should be. as @sehdev says his answer..

You can create an symlink:

ln -s /path/to/laravel/resources/images /path/to/laravel/public/images

Although as other users have already pointed out, the resource directory is not intended to be used publicly.

I agree with @sehdev.

However, if you still want to serve your image from resources directory, here is a solution that gets the job done.

In your view:

<img src="/your-image" />

In Route:

Route::get('/your-image', function ()
{
   $filepath = '/path/to/your/file';

    $file = File::get($filepath);
    $type = File::mimeType($filepath);

    $response = Response::make($file, 200);
    $response->header("Content-Type", $type);
    $response->header("Content-Length", File::size($filepath));
    return $response;
})

this is not the best solution. I suggest you to move your assets to public directory.

Edit: Use laravel functions. I suggest not to take file path from url because it may subject to Directory Traversal.

Related