你可以这样做
//获取您的数据(您的部分代码)
$posts = DB::table('blog_posts') -where(['post_type' => 1, 'post_status' => 1]) ->orderBy('id', 'desc') ->take(5)->get();
//添加 post_seo
foreach ($posts as $post) { $post->post_seo = seoUrl($post->post_title); }
//设置结果数组
$data['data'] = $posts; $data['success'] = true;
//回应
$response = response()->json($data);
//或者如果您想要返回它
return response()->json($data);
编辑
使用时,你也可以做得更好一些Eloquent
.如果你有这样的模型(你需要添加有效的命名空间和use
语句)
class BlogModel extends Model { protected $table = 'blog_posts'; protected $appends = ['post_seo']; public function getPostSeoAttribute($value) { return seoUrl($this->post_title); } }
(添加post_seo
属性的访问器并post_seo
在转换为数组时添加到结果中)
你现在可以做(比前面的例子更短的语法):
//获取您的数据
$posts = BlogPost::where('post_type',1) ->where('post_status',1) ->orderBy('id', 'desc') ->take(5)->get();
//回应
$response = response()->json(['data' => $posts, 'success' => true]);