Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/231.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php Laravel 5-在Rest API服务器上自定义JSON响应_Php_Json_Laravel 5 - Fatal编程技术网

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

Php Laravel 5-在Rest API服务器上自定义JSON响应,php,json,laravel-5,Php,Json,Laravel 5,我对Laravel是全新的,我正在将我的应用程序从Slim框架迁移到Laravel 5。 通过谷歌搜索,我还没有找到多少关于如何定制JSON响应的信息。假设我有: 型号 <?php namespace App; use Illuminate\Database\Eloquent\Model; class User extends Model { protected $visible = [ 'username', 'posts', ]; } 如果我想

我对Laravel是全新的,我正在将我的应用程序从Slim框架迁移到Laravel 5。 通过谷歌搜索,我还没有找到多少关于如何定制JSON响应的信息。假设我有:

型号

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    protected $visible = [
        'username', 'posts',
    ]; 
}
如果我想在JSON对象中输出该数据,如:

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

有人知道有没有图书馆可以处理这类事情吗?还是有人已经在拉雷维尔解决了这个问题

注意:我知道我可以编写一个中间件来“修改”响应,但我不确定它是否是正确的解决方案,并且检查中间件响应是否应该包含错误也很痛苦

谢谢。

你试过了吗

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

是一种迟来的反应,但可能对其他人有帮助

您可以通过响应工厂在您的项目上创建提供者来解决此问题,下面是一个成功错误响应的示例:

<?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()
    {
        //
    }
}
完成后,由于提供程序已经聚合,您只需使用响应帮助程序调用宏并传递相应的属性即可。例如:

$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');
}

当然,如果我对该数组进行json_编码,而不是仅对User:all()进行编码,它就会工作。。。。这是我目前在Slim上使用的方法。。我有一个静态函数,它接受数据和错误参数,并相应地返回响应数组。。。我在寻找的是拉拉维尔身上的某种东西。。谢谢你的关注
<?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()
    {
        //
    }
}
'providers' => [
    ...

    App\Providers\ResponseServiceProvider::class,
]
$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');
}