Laravel9 多种方式把集合数据转为 JSON 数据

作者: 温新

分类: 【Laravel】

阅读: 2207

时间: 2022-09-04 16:23:57

hi,我是温新,一名PHPer

本篇文章将学习使用 4 种方法,将数据转为 JSON 格式。

准备工作

一:创建一个项目

二:定义路由

<?php
// routes/web.php
    
use Illuminate\Support\Facades\Route;


Route::get('users', [\App\Http\Controllers\Test\UserController::class, 'index']);

三:创建一个控制器

<?php
// Test/TestController.php
namespace App\Http\Controllers\Test;

use App\Http\Controllers\Controller;

class UserController extends Controller
{
}

toJson() 方法将模型数据转为 JSON 数据

获取所有结果

<?php

namespace App\Http\Controllers\Test;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;

class UserController extends Controller
{
    public function index(Request $request)
    {
        return User::query()->latest()->get()->toJson();
    }
}

返回结果

[
  {
    "id": 282,
    "name": "Ms. Burdette Fadel",
    "email": "brandon.mills@example.net",
    "email_verified_at": "2022-09-04T15:55:43.000000Z",
    "created_at": "2022-09-04T15:55:47.000000Z",
    "updated_at": "2022-09-04T15:55:47.000000Z"
  },
  {
    "id": 283,
    "name": "Kenny Schimmel II",
    "email": "arvid57@example.com",
    "email_verified_at": "2022-09-04T15:55:43.000000Z",
    "created_at": "2022-09-04T15:55:47.000000Z",
    "updated_at": "2022-09-04T15:55:47.000000Z"
  }
]

获取一条数据

public function index(Request $request)
{
    return User::query()->find(1)->toJson();
}

返回结果

{
  "id": 1,
  "name": "Laverna Smitham",
  "email": "claudine.reichert@example.com",
  "email_verified_at": "2022-09-04T15:55:43.000000Z",
  "created_at": "2022-09-04T15:55:46.000000Z",
  "updated_at": "2022-09-04T15:55:46.000000Z"
}

json_encode() 将模型数据转为 JSON 数据

public function index(Request $request)
{
    // 所有数据
    $users = User::query()->latest()->get();
    
    // 一条数据
    // $user = User::query()->latest()->find(1);

    return json_encode($users);
}

集合数据转为 JSON 数据

public function index(Request $request)
{
    $users = collect([
        ['id' => 1, 'name' => 'lisi',   'age' => 18],
        ['id' => 2, 'name' => 'wangwu', 'age' => 18],
    ]);

    return $users->toJson();
}

使用 response json

public function index(Request $request)
{
    $users = User::query()->where('id', '<', 5)->latest()->get();
    return response()->json($users);
}
请登录后再评论