PHP code example of chuoke / response4laravel

1. Go to this page and download the library: Download chuoke/response4laravel library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

chuoke / response4laravel example snippets


use Chuoke\Response4Laravel\Concerns\ResponseHelper;

use Chuoke\Response4Laravel\Response;

protected function apiResponse() {
    return Response::make();
}

$this->response()->ok(); // or $this->response()->ok($data)
$this->response()->created($data, 'The data was created successfule!');
$this->response()->notFound('The data not exists');
$this->response()->badRequest('Your submit is wrong.');

$this->response()->ok($userResource);
// output content: {"data":{"id":1,"name":"name"}}

$this->response()->ok($userCollectionResource);
// output content: {"data":[{"id":1,"name":"name"},{"id":2,"name":"name2"}]}

$this->response()->collectionWrap('users')->ok($userCollectionResource);
// output content: {"users":[{"id":1,"name":"name"},{"id":2,"name":"name2"}]}

$users = User::query()->paginate($request->get('per_page'));

return $this->ok(UserResource::collection($users));
// output content: {"data":[{"id":1,"name":"user1"},{"id":2,"name":"user2"},{"id":3,"name":"user3"}],"links":{"first":"http:\/\/localhost\/paginator?page=1","last":"http:\/\/localhost\/paginator?page=4","prev":null,"next":"http:\/\/localhost\/paginator?page=2"},"meta":{"current_page":1,"from":1,"last_page":4,"links":[{"url":null,"label":"&laquo; Previous","active":false},{"url":"http:\/\/localhost\/paginator?page=1","label":"1","active":true},{"url":"http:\/\/localhost\/paginator?page=2","label":"2","active":false},{"url":"http:\/\/localhost\/paginator?page=3","label":"3","active":false},{"url":"http:\/\/localhost\/paginator?page=4","label":"4","active":false},{"url":"http:\/\/localhost\/paginator?page=2","label":"Next &raquo;","active":false}],"path":"http:\/\/localhost\/paginator","per_page":3,"to":3,"total":10}}

protected function response()
{
    return Response::make()
        ->responseUsing(function ($data, $status, $message) {
            return response()->json([
                'code' => $status,
                'message' => $message ?: 'success',
                'data' => is_array($data) && array_key_exists('data', $data) && count($data) === 1 ? $data['data'] : $data,
            ], 200);
        });
}

//
$this->response()->ok(new UserResource(User::first()));
// output content: {"code":200,"message":"success","data":{"id":1,"name":"user1"}}