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

我在Laravel上是全新的,我正在将我的应用程序从Slim Framework迁移到Laravel 5.
Googling 我没有找到有关如何自定义JSON响应的更多信息。 假设我有:</ p>

模型</ strong> </ p>

 &lt;?php 

namespace App;

use Illuminate \ Database \ Eloquent \ Model;

class用户扩展Model
{
protected $ visible = [
'username','posts',
]; \ N}
</代码> </ PRE>

<强> CONTROLLER </强> </ p>

 <代码>&LT; PHP 

命名空间 App \ Http \ Controllers;

use [...]

/ * * * n *隐式控制器

  • /
    class UserController扩展Controller
    {
    公共函数getIndex()
    {\ n return response() - &gt; json(User :: all(),200);
    }
    }
    </ code> </ pre>

    ROUTE </ strong > </ p>

      Route :: controller('users','UserController'); 
    </ code> </ pre>

    如果我想要什么 在JSON对象中输出该数据,如:</ p>

      {“success”:bool,“message”:string,“data”:array} 
    //在这种情况下 'array'将是User :: all()
    </ code> </ pre>

    ?</ p>

    有谁知道是否有一个库来处理这个问题 什么东西? 或者有人已经以某种方式在laravel中解决了这个问题吗? </ p>

    N.B。 我知道我可以编写一个中间件来“修改”响应,但我不确定它是否是正确的解决方案,检查中间件是否应该包含错误也很痛苦。</ p> \ n

    谢谢。</ p>
    </ div>

展开原文

原文

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个回答



是一种迟到的反应,但也许它会对某些人有所帮助。</ p>

你 可以通过Response Factory在项目中创建提供商来解决这个问题,以下是成功</ strong>和错误</ strong>响应的示例:</ p>

 <  code>&lt;?php 
//将此文件放在项目的提供者文件夹
namespace App \ Providers;

use Illuminate \ Support \ ServiceProvider;
use Illuminate \ Routing \ ResponseFactory;

class ResponseServiceProvider扩展 ServiceProvider
{
/ **
*引导应用程序服务。

  • @return void
  • / 公共功能启动(ResponseFactory $ factory) { $ factory-&gt; 宏('成功',函数($ message ='',$ data = null)使用($ factory){ $ format = [ 'status'=&gt;'ok', 'message'=&gt; ; $ message, 'data'=&gt; $ data,

];

返回$ factory-&gt; make($ fo rmat);
});

$ factory-&gt;宏('错误',函数(字符串$ message ='',$ errors = [])使用($ factory){
$ format = [

'status'=&gt; '错误',
'消息'=&gt; $ message,
'errors'=&gt; $ errors,
];

返回$ factory-&gt; make($ format);
});
}

/ **
*注册应用程序服务。

  • \ n * @return void
  • /
    公共函数寄存器()
    {
    //
    }
    }
    </ code> </ pre>

    然后在您的提供者上 config / app.php中的值只需添加类:</ p>

     'providers'=&gt;  [
    ...

    App \ Providers \ ResponseServiceProvider :: class,
    ]
    </ code> </ pre>

    由于提供程序已经聚合,因此已完成, 您可以使用响应助手</ strong>调用宏来传递相应的属性。 例如:</ p>

      $ user = User :: find(1);  

if($ user){
return response() - &gt; success('您的自定义成功消息',$ user);
} else {
return response() - &gt;错误('您的自定义 错误消息','验证错误或其他');
}
</ code> </ pre>
</ div>

展开原文

原文

Is a kinda late response but maybe it'll be helpfull for someone further.

You can solve this with a Response Factory creating a Provider on your project, here is an example for Success and Error responses:

<?php
// Place this file on the Providers folder of your project
namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Routing\ResponseFactory;

class ResponseServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot(ResponseFactory $factory)
    {
        $factory->macro('success', function ($message = '', $data = null) use ($factory) {
            $format = [
                'status' => 'ok',
                'message' => $message,
                'data' => $data,
            ];

            return $factory->make($format);
        });

        $factory->macro('error', function (string $message = '', $errors = []) use ($factory){
            $format = [
                'status' => 'error', 
                'message' => $message,
                'errors' => $errors,
            ];

            return $factory->make($format);
        });
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

Then on your providers value placed in config/app.php just add the class:

'providers' => [
    ...

    App\Providers\ResponseServiceProvider::class,
]

And it's done, as the provider is already aggregated, you can just call the macro using the response helper passing the respectives attributes. Eg:

$user = User::find(1); 

if($user) {
   return response()->success('Your custom success message', $user);
} else {
   return response()->error('Your custom error message', 'Validation errors or else');
}



您是否尝试</ p>

  return response() - &gt; json([\  n'成功'=&gt; true,
'消息'=&gt;'字符串',
'数据'=&gt;用户::所有()

] ;;
</ code> </ pre>

?</ p>
</ div>

展开原文

原文

Did You try

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

?

douba3975
douba3975 当然,如果我json_encode那个数组而不仅仅是User:all()....这是我正在Slim上使用的方法..我有一个接受数据和错误参数的静态函数,并返回响应数组 因此......我正在寻找的是Laravel内置的东西..感谢您的关注
4 年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐