How to get avatar url which are stored at storage

2019-07-24 20:19发布

问题:

I want to get the url of stored avatar inside the storage directory, i am using laravel 5.4.

Actually i am using following method for uploading image and get the url.

Uploading Image:

<input type="file" class="form-control" value="{{ old('u_avatar') }}" name="u_avatar" />

In the Controller

$UserModel->u_avatar = $request->file('u_avatar')->store('avatars'); // Uploading Files properly in the storage/app/avatars

Getting Image

I have tried following two methods for getting the images, but both are not working

First Method

In the view file

<img src="{{ asset('storage/app') }}/{{ $User->u_avatar }}" class="img-responsive" /> // Not Working

Second Method In the Controller

$User = UserModel::find($id);
//For Image
$path =  asset('storage/app/'.$User->u_avatar);// Not working 

I would like to request to you kindly guide me i am doing in right way or not? In this reference the person is saying

storage is not public. You cannot save files there then create web links to them. This thread is about being able to use laravel to intercept the call for the image, get it from private storage and stream the file to the client.

So can someone what is the best way to store the files in laravel5.4 and how can get in proper way. I would like to appreciate. Thank You.

回答1:

storage directory is not accessible from the web, so you need to create a symlink.

The public disk is intended for files that are going to be publicly accessible. By default, the public disk uses the local driver and stores these files in storage/app/public. To make them accessible from the web, you should create a symbolic link from public/storage to storage/app/public. This convention will keep your publicly accessible files in one directory that can be easily shared across deployments when using zero down-time deployment systems like Envoyer.

To create the symbolic link, you may use the storage:link Artisan command:

php artisan storage:link

Of course, once a file has been stored and the symbolic link has been created, you can create a URL to the files using the asset helper:

echo asset('storage/file.txt');

https://laravel.com/docs/5.4/filesystem#the-public-disk