Skip to content

⭐️ Unification of API responses for Laravel projects inspired by telegram api responses

License

Notifications You must be signed in to change notification settings

kolirt/laravel-api-response

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

10 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Laravel Api Response

Unification of API responses for Laravel projects inspired by telegram api responses

Structure

Buy Me A Coffee

Getting started

Requirements

  • PHP >= 8.1
  • Laravel >= 10

For lesser versions of Laravel or PHP, use the v2

Installation

composer require kolirt/laravel-api-response

Usage

Example

Error response

return api()
        ->error()
        ->setCode(400) // default code 400

        ->setDescription(['Description #1', 'Description #2'])
        // or
        ->setDescription('Description')
        
        ->setData(['Data #1', 'Data #2'])
        // or
        ->setData('Data')
        
        ->render();
[
    'ok' => false,
    'error_code' => 400,
    
    'description' => ['Description #1', 'Description #2'],
    // or
    'description' => 'Description',
    
    'result' => ['Data #1', 'Data #2'],
    // or
    'result' => 'Data',
]

Success response

return api()
        ->success()
        ->setCode(200) // default code 200

        ->setDescription(['Description #1', 'Description #2'])
        // or
        ->setDescription('Description #1')
        
        ->setData(['Data #1', 'Data #2'])
        // or
        ->setData('Data')
        
        ->render();
[
    'ok' => true,
    
    'description' => ['Description #1', 'Description #2'],
    // or
    'description' => 'Description',
    
    'result' => ['Data #1', 'Data #2'],
    // or
    'result' => 'Data',
]

Methods

error

Mark response as error

return api()->error();

success

Mark response as success

return api()->success();

setCode

Set specific code to response. Available codes

return api()->setCode($code);

setDescription

Add description to response

return api()->setDescription(['Description #1', 'Description #2']);
// or
return api()->setDescription('Description');

setErrors

Add errors to response

return api()->setErrors([
    'first_name' => 'Error message', 
    'last_name' => ['Error message 1', 'Error message 2']
]);

abort

Abort response with error

return api()->abort('Error message', 400);

cookie

Add cookie to response

return api()->cookie(cookie('token', 'asdsadsadas', 60 * 3));

setData

Add data to response

return api()->setData(['Data #1', 'Data #2']);
// or
return api()->setData('Data');

render

Render response

return api()->render();

FAQ

Check closed issues to get answers for most asked questions

License

MIT

Other packages

Check out my other packages on my GitHub profile