izdb's avatar
Level 1

CMS build, file path issue

I'm building a CMS for a small project so I can learn how to use Laravel properly. I am writing a system to upload and show some images, however I am confused about the correct way to access them once uploaded.

    public function storeImage(Request $request)
    {

        $request->file('image')->store('public/images');
       
        $filename = md5_file($request->file('image')) . '.' .  $request->file('image')->extension();
        $img = new Image;
    $img->path = 'storage/images/'.$filename;
        $img->save();

        return back();
    }

This works fine, and I have symlinked storage as suggested, however if I use the $filename variable from the database I get a 404. What is the correct path to generate to insert as an inline image src attribute here?

The image tag looks like this: <img src="storage/images/89cdd31f2e0eeacceff96c2a0abb252f.jpeg" alt="pig"> I can see that in my public folder there is a little symlinked storage folder in PHPStorm.

0 likes
7 replies
tykus's avatar

Your $img->path should save to public, because storage is not accessible from the web root (public)

$img->path = '/images/'.$filename;
1 like
izdb's avatar
Level 1

Still get a 404 - my-site.dev/images/89cdd31f2e0eeacceff96c2a0abb252f.jpeg.

The path the image is being put in is my-site/storage/app/public/images

tykus's avatar

What is your symlink?

If you are mapping public/storage to /storage/app/public/ then:

$img->path = '/storage/images/'.$filename;
izdb's avatar
Level 1

Storage links to public. It doesn't work! Could it be a permissions issue?

tykus's avatar

Permissions shouldn't be a problem.

Have you used the artisan command to create the link, or did you use ln yourself? In your project's public directory, do you have something like:

lrwxr-xr-x  1 tykus  staff    43B 28 Sep 01:30 storage -> /Users/tykus/src/{PROJECT_ROOT}/storage/app/public

You should be able to use the asset('storage/images/'.$filename;) helper method to retrieve the path to the image.

izdb's avatar
Level 1
lrwxr-xr-x   1 me  staff    54 Sep 27 19:32 storage -> /Users/me/Projects/my-site/storage/app/public

Oh do I have to use the asset command? I can't use the path directly?

<img src="{{$home->image->path}}" >
izdb's avatar
Level 1

php artisan storage:link does not work with homestead. Instead delete the folder, manually recreate them on the machine using homestead ssh and ln -s ~/projects/my-website/storage/app/public/ ~/projects/my-website/public/storage.

Please or to participate in this conversation.