laravel-json返回约束

讲解

在开发中我们有时候需要约束返回的字段,或者提交
的时候也约束一下需要提交的字段

约束返回字段

1.建立文件夹responses

如果是模块开发请添加二级分类

app\response\admin

在里面建立返回类

app\response\admin\AdminRespons.php

示例代码

使用

在控制器文件中使用

#单字段返回代码示例
<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\responses\admin\AdminResponse;


class TestController extends Controller
{
    //这里只有单个数据才可以返回
    public function index()
    {
        return response()->json(new AdminResponse(User::first()));
    }
}

多字段返回代码示例

<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\responses\admin\AdminResponse;


class TestController extends Controller
{
    //
    public function index()
    {
        //多字段返回需要使用map方法
       $user= User::get()->map(function ($user){
           return new AdminResponse($user);
        });
        return response()->json($user);
    }
}

返回字段约束已经写完了,请求提交返回类似但是现在暂时用不到以后用到了补充

posted @ 2020-12-31 18:02  以己为镜  阅读(72)  评论(0编辑  收藏  举报