Muhammad Anwar Shamim
Muhammad Anwar Shamim

Reputation: 73

Laravel API return image from public folder with database data

I want to return image with data.

$ads = DB::table('ads')->whereRaw('category_id=' .$id)->orderBy('id', 'desc')->get();

$filename = public_path().'/uploads/images/'.$ads->ad_image;
$filename = (file_get_contents($filename));
$image = Array('image'=>json_encode(base64_encode($filename)));
$ads[0]->image = $image;

return $ads; 

Upvotes: 2

Views: 24635

Answers (2)

Prakash Poudel
Prakash Poudel

Reputation: 443

$filename = asset('/uploads/images/'.$ads->ad_image);

Upvotes: 0

jaysingkar
jaysingkar

Reputation: 4435

Assuming you want to show the images to the user on the page stored in laravel's storage directory, You can do the following implementation:

Create a controller to fetch and return the image as a response.

<?php
namespace App\Http\Controllers;

use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\View;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Response;
Use DB;


class PhotoController extends Controller
{
    public function image($fileName){
        $path = public_path().'/uploads/images/'.$fileName;
        return Response::download($path);        
    }
}

Add the Route to handle the image request

Route::get('image/{filename}',PhotoController @image);

Now, to access the image , lets say in image tag

<img src="image/abc.jpg">

PS: This method of serving images will have little overhead with respect to direct link of image...
In case, your images are public, you can simply create symbolic link of the directory where you have stored the images into the public directory.

Upvotes: 10

Related Questions