1

我正在从事 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",
                "post_content": "<p>content</p>",
                "category_id": "1",
                "image": "https://www.mylink.com/uploads/posts/image1.png",
                "category": {
                    "id": 1,
                    "name": "category1",
                }
            },
        ]
4

1 回答 1

2

您可以简单地 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();
于 2020-10-18T20:31:28.557 回答