red17
red17

Reputation: 97

How do I display image path stored in database PHP? (Laravel Orchid)

I want to display images in my Laravel Orchid admin panel. Orchid stores the uploaded images in this folder, with the folder name being the date it was uploaded:

storage\app\public\2021\04\21\<name>

Laravel stores the image original name, path, extension etc in a special table called 'attachments'. It is linked to my main table called 'users' by an id, image_id in 'users' and id in 'attachments'. In my database, the path is stored as the date, e.g:

2021/04/21/

I did this SQL join query to retrieve the image:

$image = $user->image_id;
$images = DB::table('users')
          ->leftJoin('attachments', 'users.image_id', '=', 'attachments.id')
          ->where('users.image_id', '=', $image)
          ->get(['name', 'original_name', 'path', 'extension']);
            
            foreach($images as $image)
            {
                
                $image_url = $image->path.$image->name.'.'.$image->extension;
                return "<img src='{$image_url}'
                <span class='small text-muted mt-1 mb-0'>{$image->original_name}</span>";
            }

I can display the original name however the image does not display. I would like to know if there is anything wrong with the way i retrieved the image. Thank you.

Upvotes: 2

Views: 2027

Answers (2)

Andrew
Andrew

Reputation: 1823

The public path to your images is configured in your config\filesystems.php file.

There will be a section that looks something like this:

'public' => [
            'driver' => 'local',
            'root' => storage_path('app/public'),
            'url' => env('APP_URL').'/storage',
            'visibility' => 'public',
        ],

You likely need to correct the image's path you are saving into the database to match what's configured here, note the 'url' value matches what you mentioned it the working location to your photos.

Upvotes: 1

tuhinhossain
tuhinhossain

Reputation: 41

Assuming $image_url="2021/04/21/12876b4a034032120b0a3cc3972f19cf2411aaaf.png" and your file is in /storage/public/2021/04/21/12876b4a034032120b0a3cc3972f19cf2411aaaf.png

As the image is in storage path you can create a route which response the image.

Route::get('/image/{path}', function ($path) {
   return \Illuminate\Support\Facades\Storage::disk('public')->response($path);
})->where('path', '.*')->name('show.image');

And replace your return "<img src='{$image_url}' with return "<img src='{route('show.image',['path'=>$image_url])}'

Upvotes: 0

Related Questions