dongtai6741 2016-02-06 12:03
浏览 59

Laravel 5 - 在Rest API服务器上自定义JSON响应

I am completely new on Laravel, I am migrating my application from Slim Framework to, indeed, Laravel 5. Googling I haven't find much information about how to customize a JSON response. Let's say I have:

MODEL

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    protected $visible = [
        'username', 'posts',
    ]; 
}

CONTROLLER

<?php

namespace App\Http\Controllers;

use [...]

/* *
 *  Implicit controller
 */
class UserController extends Controller
{
    public function getIndex()
    {
        return response()->json(User::all(), 200);
    }
}

ROUTE

Route::controller('users', 'UserController');

What if I want to output that data in a JSON object like:

{"success": bool, "message": string, "data": array} 
// in this case 'array' would be User::all()

?

Does anyone know whether there's a library to handle this kind of stuff? Or Has anyone already addressed this in laravel somehow?

N.B. I know I can write a Middleware to "modify" the response, but I am not sure it is the right solution, and it is also painful to check into the middleware whether the response should contain an error or not.

Thank you.

  • 写回答

2条回答 默认 最新

  • douyi0902 2016-02-06 12:23
    关注

    Did You try

    return response()->json([
        'success'=>true, 
        'message'=>'string', 
        'data'=>User::all()
    ]);
    

    ?

    评论

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题