Peter Fox
Peter Fox

Reputation: 21

I cant load uploaded images from subfolders in laravel

I've tried to let users upload project-based images in dynamic subfolders. They can be uploaded, but they cant get fetched in the frontend. It seems like there is a permission problem.

Its Laravel 5.8. I've tried it via Storage: link but it doesn't work so far. Maybe I'm doing something wrong.

That's my Testupload function, it stores the files in e.g: storage/app/35/image.jpg

public function store($file, $project){
        $filepath = $project->id.'/';
        if($file){
            Storage::disk('local')->put( $filepath .'/image.jpg', File::get($file));
        }
    }

That's my route:

Route::get('projectimage/{filename}', [
    'uses' => 'projectController@getProjectImage',
    'as' => 'getProjectImage'
]);

Here is my Blade template Part:

 @if (Storage::disk('local')->has($project->id.'/image.jpg'))
                    <img src="{{ route('getProjectImage', [$project->id.'/image.jpg'])}}" alt="">
@endif

Thats how to get the images:

    public function getProjectImage($filename){
        $file = Storage::disk('local')->get($filename);
        return new Response($file, 200);
    }

I didnt change any config file, but I didphp artisan storage:link` and tried it via 'public' instead of 'local'. It didn't work. But it always works without Subfolders. How can I fix this?

I expect to get the images rendered in FrontEnd. The resulted Link is: src="http://myproject.test/projectimage/35/image.jpg"

Now i've got a strange Point... if i hard code the subfolder it works.

$file = Storage::disk('local')->get('60/'.$filename);

My Solution:

blade template:

@if (Storage::disk('local')->has($project->id.'/image.jpg'))
                    <img src="{{ route('getProjectImage',['filename'=>'image.jpg', 'projectid'=>$project->id])}}" alt="">
                @endif

controller:

    public function getProjectImage($filename, $project_id){

         $file = Storage::disk('local')->get($project_id.'/'.$filename);
        return new Response($file, 200);

    }

Feel free to improve my code. :*

Upvotes: 0

Views: 143

Answers (2)

Peter Fox
Peter Fox

Reputation: 21

Ok, it seems that Laravel kinda doesn't allow dynamic string inputs on the view side to fetch serverdata. I solved it by adding the project ID and imagename as parameters via route. The path will be build in the controller. I will update my post.

Upvotes: 0

antoiba86
antoiba86

Reputation: 78

In the function "getProjectImage".

It wouldn't be better to use "return response()->file($pathToFile);"

I leave here the link to the documentation. https://laravel.com/docs/5.8/responses#file-responses

Upvotes: 0

Related Questions