Laravel Rest API,获取与存储在上载/帖子中的数据库中的数据关联的图像的完整链接

问题描述

我正在Laravel项目中工作,遇到一个问题。我希望我的ApiController.PHP上的函数能够为我带来POST表中图像的完整链接,并存储在上载/发布中。 所以我尝试了这种方法,我怎么能得到这个结果?

//ApiController
    <?PHP
    namespace App\Http\Controllers;
    use Illuminate\Support\Arr;
    use Illuminate\Http\Request;
    use Illuminate\Support\Str;
    use Carbon\Carbon;
    use App\Category;
    use App\Post;
    
    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","image": "https://www.mylink.com/uploads/posts/image1.png","category": {
                    "id": 1,}
            },]

解决方法

您可以简单地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();