Laravel 休息 api,获取与存储在 uploads/posts 中的数据库中的数据关联的完整图像 link
Laravel rest api, get the full link of the images associated with the data in database stored in uploads/posts
我正在处理 Laravel 项目项目,遇到了一个问题。我希望我的 ApiController.php 功能能够将来自 POST table 的完整 link 图像带给我,存储在上传/帖子中。
所以我尝试了这个方法,我怎么能得到这个结果?
//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",
}
},
]
那么如何得到完整的link图像呢?
//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();
我正在处理 Laravel 项目项目,遇到了一个问题。我希望我的 ApiController.php 功能能够将来自 POST table 的完整 link 图像带给我,存储在上传/帖子中。 所以我尝试了这个方法,我怎么能得到这个结果?
//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",
}
},
]
那么如何得到完整的link图像呢? //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();