Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Retrieve Images from storage to view

Tags:

laravel

I am using below code to store the uploaded file

 $file = $request->file($file_attachment);
        $rules = [];
        $rules[$file_attachment] = 'required|mimes:jpeg|max:500';
        $validator = Validator::make($request->all(), $rules);
        if ($validator->fails()) {
            return redirect()->back()
                ->with('uploadErrors', $validator->errors());
        }

        $userid = session()->get('user')->id;
        $destinationPath = config('app.filesDestinationPath') . '/' . $userid . '/';
        $uploaded = Storage::put($destinationPath . $file_attachment . '.' . $file->getClientOriginalExtension(), file_get_contents($file->getRealPath()));

The uploaded files are stored in storage/app/2/filename.jpg

I want to show back the user the file he uploaded. How can i do that?

$storage = Storage::get('/2/filename.jpg');

I am getting unreadable texts. I can confirm that the file is read. But how to show it as an image to the user.

Hope i made my point clear.

Working Solution

display.blade.php

<img src="{{ URL::asset('storage/photo.jpg') }}" />

web.php

Route::group(['middleware' => ['web']], function () {
    Route::get('storage/{filename}', function ($filename) {
        $userid = session()->get('user')->id;
        return Storage::get($userid . '/' . $filename);
    });
});

Thanks to: @Boghani Chirag and @rkj

like image 250
Alaksandar Jesus Gene Avatar asked Jun 23 '18 03:06

Alaksandar Jesus Gene


People also ask

How do you get the storage path in blade laravel?

“laravel storage path url in blade” Code Answer's$currentURL = URL::current(); PHP. $url = URL::to("/"); or use $url = url('/'); PHP. $route = Route::current()->getName(); PHP. $prefix = Request::route()->getPrefix(); PHP.


1 Answers

Uploaded like this

$uploadedFile = $request->file('photo');
$photo = "my-prefix" . "_" . time() . "." . $uploadedFile->getClientOriginalExtension();
$photoPath = \Illuminate\Support\Facades\Storage::disk('local')->putFileAs(
   "public/avatar",
   $uploadedFile,
   $photo
);

and then access like this

<img src="{{ asset('storage/avatar/'.$filename) }}" />
like image 173
Abdul Manan Avatar answered Oct 04 '22 05:10

Abdul Manan