lazerg/laravel-response-helpers

为laravel提供响应助手

v2.1.0 2024-05-04 13:07 UTC

This package is not auto-updated.

Last update: 2024-09-21 15:09:30 UTC


README

Version Downloads count Repository count Last commit Stars count

助手,用于以相同结构化的格式发送API响应。响应总是包含消息和数据。

{
    "message": "Successfully updated",
    "data": {
        "id": 1,
        "name": "John Doe",
        "email": "johndoe@example.com"
    }
}

安装

只需通过composer在您的Laravel API中引入此包。

composer require lazerg/laravel-response-helpers

之后,在主控制器 app/Http/Controllers/Controller.php 中引入特性 \Lazerg\LaravelResponseHelpers\ResponseHelpers;

不使用资源化响应的使用方法

    # Response with success message
    $this->responseMessage('Successfully updated');

    # Response with error message
    $this->responseMessage('Failed to update', 400);

    # Successful response with data
    $this->responseData($user);

    # Error response with data
    $this->responseData($user, 400);

    # Response with success message and data
    $this->response('Successfully updated', $user);

    # Response with error message and data
    $this->response('Failed to update', $user, 400);

使用资源化响应的使用方法

    # Success response with resourceful data
    $this->responseResourceful(UsersResource::class, $users);

    # Error response with resourceful data
    $this->responseResourceful(UsersResource::class, $users, 400);

    # Success response with resourceful message and data
    $this->responseJsonResourceful(UsersResource::class, $users, 'Successfully updated');

    # Error response with resourceful message and data
    $this->responseJsonResourceful(UsersResource::class, $users, , 'Failed to update', 400);

测试

$this->getJson(route('users.index'))
    ->assertOk()
    ->assertJsonCountData(5)

    # amount of $users->first()->posts
    ->assertJsonCountData(2, '0.posts')
    ->assertJsonStructureData([
        ['id', 'name', 'email']
    ]);
    ->assertJsonData([
        'id' => 1,
        'name' => 'John Doe',
        'email' => 'johndoe@example.com'
    ]);

响应示例

不使用资源化响应的数据

hello hello

不使用资源化响应的分页

hello hello

使用资源响应的数据

hello hello

使用资源响应的分页

hello hello