Search code examples
phpimagelaraveluploadcontrollers

LARAVEL - Displaying images from the storage folder


I'm new to Laravel and was wondering if someone can help me out with a simple image upload.

I have a form that allows a user to create a profile and upload and avatar for their profile during the process. This all works perfectly. Here is the code from my controller:

if (request()->hasFile('avatar')) {

        $file = request()->file('avatar');

        $file->storeAs('avatars/' . auth()->id(), 'avatar.jpg');
    }

The image is saved within storage/app/avatars/USER-ID/avatar.jpg

I'm not sure how to display the image from this folder. I've looked for solutions but I am unable to use php artisan storage:link as it is not my server. How do I go about this without using the storage link? Can I create a link manually?

If someone could explain a solution to me that would be perfect!

Just ask if you need any code snippets.

Thanks!


Solution

  • You will need to access the protected files using a route the plugs into a controller that can access the files and pass it to the view.

    I would also recommend using the package intervention/image it can be installed by

    composer require intervention/image

    See below to on accessing the image:

    // Your route in web.php

    // Public route to show user avatar
    Route::get('avatars/{id}/{image}', [
        'uses'      => 'TheNameOfYourController@userProfileAvatar'
    ]);
    

    // In your controller file. In this example according the name of what we have above it would be userProfileAvatar()

    namespace App\Http\Controllers;
    
    use Illuminate\Http\Request;
    use Image;
    
    class TheNameOfYourController extends Controller
    {
    
        /**
         * Show user avatar
         *
         * @param $id
         * @param $image
         * @return string
         */
        public function userProfileAvatar($id, $image)
        {
            return Image::make(storage_path() . '/avatars/' . $id . '/' . $image)->response();
        }
    
    }
    

    // Your blade view to display the image

    <img src="images/profile/{{ \Auth::user()->id }}/avatar.jpg" alt="{{ \Auth::user()->name }}">
    

    Here are some references but this intances that go one step further and save the file path the database upon upload:

    // Route Example

    // Controller Example

    // View Examples