Laravel rest api,获取与数据库中存储的上传/帖子中的数据相关联的图像的完整链接



我正在进行Laravel项目,遇到了一个问题。我希望我在ApiControlle.php上的函数能为我带来POST表中图像的完整链接,存储在上传/发布中。所以我尝试了这个方法,如何才能得到这个结果?

//ApiController
<?php
namespace AppHttpControllers;
use IlluminateSupportArr;
use IlluminateHttpRequest;
use IlluminateSupportStr;
use CarbonCarbon;
use AppCategory;
use AppPost;

class ApiController extends Controller
{
//
public function getposts(){
$post = Post::select('post_title','post_content','category_id','image')
->with('category')
->get();
$categories=Category::all();
return response()->json($post, 200, [], JSON_UNESCAPED_UNICODE);
}
}

我得到的结果

Api Result
[
{
"post_title": "post title 1",
"post_content": "<p>content</p>",
"category_id": "1",
"image": "uploads/posts/image1.png",
"category": {
"id": 1,
"name": "category1",
}
},
]

那么如何获得图像的完整链接呢?//https://www.mylink.com/uploads/posts/image1.png我想展示的结果

//result i want
[
{
"post_title": "post title 1",
"post_content": "<p>content</p>",
"category_id": "1",
"image": "https://www.mylink.com/uploads/posts/image1.png",
"category": {
"id": 1,
"name": "category1",
}
},
]

您可以简单地foreach所有项目,如下所示:

foreach ($post as $p) {
$p->image = url($p->image);
}

或者更优雅的方式-您可以直接在查询中插入图像数据:

Post::select('post_title','post_content','category_id', DB::raw('CONCAT("'.url('/').'/", image) as image'))->get();

最新更新