Reputation: 592
I am trying to display json array of the images stored in database to come with the full URL in Laravel. I am using CONCAT()
function to concatenate the full URL of the image, but I'm getting a false URL with many dashes inside.
This is a problem in the coming output:
{
"posts": [{
"imageurl": "http:\/\/localhost:8000\/images\/1509695371.jpg"
}, {
"imageurl": "http:\/\/localhost:8000\/images\/1509695156.jpg"
}, {
"imageurl": "http:\/\/localhost:8000\/images\/1509696465.jpg"
}, {
"imageurl": "http:\/\/localhost:8000\/images\/1509697249.jpg"
}]
}
And this is the function in my controller to retrieve the images stored in database from Post table:
public function index()
{
$posts = Post::select(array(DB::raw("CONCAT('http://localhost:8000/images/', image) AS imageurl")))->get();
return response()->json(['posts' => $posts]);
}
Any help will be more appreciated!
Upvotes: 0
Views: 3899
Reputation: 217
DB::raw('CONCAT(\'http://localhost/hrms/images/logo/\', schools.image) as image')
And for dynamic use
DB::raw('CONCAT(\''.$url.'\', schools.image) as image')
Upvotes: 0
Reputation: 592
Thank you so much @Sari It's now working fine. After changing the codes to this,
public function index()
{
$posts = json_encode(Post::select(array(DB::raw("CONCAT('http://localhost:8000/images/', image) AS imageurl")))->get(), JSON_UNESCAPED_SLASHES);
return $posts;
}
Upvotes: 1
Reputation: 577
instead of doing it at the db level you could do the following in your Post
model
public function getImageUrlAttribute($value)
{
return 'http://localhost:8000/'.$this->image;
}
and access it like $post->image_url
Upvotes: 0