PHPackages                             laravelista/syndra - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [API Development](/categories/api)
4. /
5. laravelista/syndra

AbandonedArchivedLibrary[API Development](/categories/api)

laravelista/syndra
==================

Common JSON responses for an API built with Laravel.

1.2.1(10y ago)263.9k4MITPHP

Since Jul 1Pushed 9y ago2 watchersCompare

[ Source](https://github.com/laravelista/Syndra)[ Packagist](https://packagist.org/packages/laravelista/syndra)[ RSS](/packages/laravelista-syndra/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (3)Dependencies (3)Versions (6)Used By (0)

Syndra
======

[](#syndra)

[![Latest Stable Version](https://camo.githubusercontent.com/faef5fcb8e57b1ebde11e0f6607a770291e6f85a1c249cb97c2d08c587d626b9/68747470733a2f2f706f7365722e707567782e6f72672f6c61726176656c697374612f73796e6472612f762f737461626c65)](https://packagist.org/packages/laravelista/syndra)[![Total Downloads](https://camo.githubusercontent.com/6759552634d628be5eace1be150368266bfd1b6573971986513c50b6b15174b6/68747470733a2f2f706f7365722e707567782e6f72672f6c61726176656c697374612f73796e6472612f646f776e6c6f616473)](https://packagist.org/packages/laravelista/syndra)[![License](https://camo.githubusercontent.com/4f865afaea5aa146255e2cf38862cfdbe5e956152af7b59f97b02b34648be890/68747470733a2f2f706f7365722e707567782e6f72672f6c61726176656c697374612f73796e6472612f6c6963656e7365)](https://packagist.org/packages/laravelista/syndra)[![Build Status](https://camo.githubusercontent.com/c9d26f18dd91d9cd73ca15bd278a4a240274655d7ce95c6cefef28298fd5920a/68747470733a2f2f7472617669732d63692e6f72672f6c61726176656c697374612f53796e6472612e7376673f6272616e63683d312e302e30)](https://travis-ci.org/laravelista/Syndra)

[![forthebadge](https://camo.githubusercontent.com/0500e27fcd4b4f7e01d2adc0aa3f86ccf34c369c2297ec3acd9fe06320a47d52/687474703a2f2f666f7274686562616467652e636f6d2f696d616765732f6261646765732f6275696c742d62792d646576656c6f706572732e737667)](http://forthebadge.com)[![forthebadge](https://camo.githubusercontent.com/5de7d0cf67b0ea82c8336a00e008f198245e38a801302e17e63e66b8d9cfdfde/687474703a2f2f666f7274686562616467652e636f6d2f696d616765732f6261646765732f706f77657265642d62792d656c6563747269636974792e737667)](http://forthebadge.com)

Syndra is a Laravel package. It provides you with predefined JSON responses to use in your API.

Overview
--------

[](#overview)

When building an API you have to standardize it so that you can always expect the same response for similar requests.

When using resource controllers these methods usually are: `index`, `store`, `update`, `destroy`.

### Index

[](#index)

For the `index` method you want to output data. That can be achieved with `Syndra::respond($data)`. By default the status code is *200*, but you can change it manually using `Syndra::setStatusCode($statusCode)->respond($data)`. Syndra goes great with [Fractal](http://fractal.thephpleague.com/). To learn how to use them together read [Laravel API 101](https://laravelista.com/series/laravel-api-101).

Another thing that you will most likely want to do is to enable CORS. This can be achieved by setting the appropriate headers:

```
return Syndra::setHeaders([
        'Access-Control-Allow-Origin' => '*',
    ])
    ->setStatusCode($statusCode)
    ->respond($data);

```

### Store

[](#store)

In the `store` method you want to return that the resource was created. Syndra enables you to do this easily with `Syndra::respondCreated()`. This generates the following response:

```
{
    "message": "Created",
    "status_code": 201
}
```

You can customize the message by passing the message as a parameter `Syndra::respondCreated('The resource has been created!')`.

### Update

[](#update)

You can almost guess which method we use for when the resource has been updated by now; `Syndra::respondUpdated()`. By default this returns message `Updated` with status code *202*. As with `respondCreated`, you can set the message by passing it as a parameter to `respondUpdated`.

### Destroy

[](#destroy)

For the `destroy` method I like to return status code *200* with a message `Ok`. This can be done with `Syndra::respondOk()`.

By applying what you have learned so far, you can now easily build your API responses however you want and they will be consistent throughout your entire API.

Advanced Usage
--------------

[](#advanced-usage)

In this chapter I will show you how to handle most common situations which can occur in your application.

### Handling Validation Errors

[](#handling-validation-errors)

If you are using `$this->validate($request, $rules)` from your controller to validate data, you would want Syndra to return validation errors if the validation fails. To do that, go to `app/Exceptions/Handler.php` and in `render` method add this block of code:

```
if ($e instanceof ValidationException) {
    return \Syndra::respondValidationError(
        $e->validator->errors()->getMessages()
    );
}
```

If the validation fails, the response will be similar to the one bellow but with different messages:

```
{
    "error" : {
        "message": {
            "email": [
				"The email format is invalid."
			]
		},
		"status_code": 422
    }
}
```

### Handling Model Not Found Errors

[](#handling-model-not-found-errors)

Similar to handling validation errors, model not found errors are addressed in the same way. Go to `app/Exceptions/Handler.php` and in `render` method add this block of code:

```
if ($e instanceof ModelNotFoundException) {
    return \Syndra::respondNotFound();
}
```

Now every time you use `Model::findOrFail($id)` in your controller and it does not find anything you will get this JSON response:

```
{
    "error" : {
        "message": "Not Found",
		"status_code": 404
    }
}
```

### Handling Authentication &amp; Authorization Errors

[](#handling-authentication--authorization-errors)

From your `AuthController`, if the authentication attempt fails you can return `Syndra::respondUnauthorized()` or if the authenticated user lacks permissions to do something you can return `Syndra::respondForbidden()`. Both methods accept message as the first parameter.

> **Hint!** You can even pass an array instead of a string as a message.

### Handling Server Errors

[](#handling-server-errors)

In the case that something goes terribly wrong, you can shamefully respond with `Syndra::respondInternalError()`.

Installation
------------

[](#installation)

From the command line:

```
composer require laravelista/syndra
```

Include the service provider in `config/app.php`:

```
'providers' => [
    ...,
    Laravelista\Syndra\SyndraServiceProvider::class
];
```

And add a facade alias to the same file at the bottom:

```
'aliases' => [
    ...,
    'Syndra' => Laravelista\Syndra\Facades\Syndra::class
];
```

API
---

[](#api)

There are two way of working with Syndra. As a facade `Syndra::respond($data)` or as a injected dependency `$this->syndra->respond($data)`:

```
use Laravelista\Syndra\Syndra;

protected $syndra;

public function __construct(Syndra $syndra)
{
    $this->syndra = $syndra
}

```

### Common responses

[](#common-responses)

#### respond

[](#respond)

This is useful for `index` and `show` method. Use this when you want to return custom JSON output, like the one you get from [Fractal](http://fractal.thephpleague.com/).

```
Syndra::respond(array $data)
```

#### respondWithMessage

[](#respondwithmessage)

Use this for responding with messages. This returns a predefined *message* JSON template which contains the message and the status code.

```
Syndra::respondWithMessage($message='Ok')
```

**Response:**

```
{
    "message": "Ok",
    "status_code": 200
}
```

#### respondWithError

[](#respondwitherror)

Use this for responding with error messages. This returns a predefined *error* JSON template which contains the message and the status code wrapped in *error*.

```
Syndra::respondWithError($message='Error')
```

**Response:**

```
{
    "error": {
        "message": "Error",
        "status_code": 200
    }
}
```

### HTTP Status Codes 2xx

[](#http-status-codes-2xx)

#### respondOk

[](#respondok)

Use this to respond with a message **(200)**.

```
Syndra::respondOk($message='Ok')
```

#### respondCreated

[](#respondcreated)

Use this when a resource has been created **(201)**.

```
Syndra::respondCreated($message='Created')
```

#### respondUpdated

[](#respondupdated)

Use this when a resource has been updated **(202)**.

```
Syndra::respondUpdated($message='Updated')
```

### HTTP Status Codes 4xx

[](#http-status-codes-4xx)

#### respondUnauthorized

[](#respondunauthorized)

Use this when the user needs to be authorized to do something **(401)**.

```
Syndra::respondUnauthorized($message='Unauthorized')
```

#### respondForbidden

[](#respondforbidden)

Use this when the user does not have permission to do something **(403)**.

```
Syndra::respondForbidden($message='Forbidden')
```

#### respondNotFound

[](#respondnotfound)

Use this when a resource is not found **(404)**.

```
Syndra::respondNotFound($message='Not Found')
```

#### respondValidationError

[](#respondvalidationerror)

Use this when the validation fails **(422)**.

```
Syndra::respondValidationError($message='Validation Error')
```

### HTTP Status Codes 5xx

[](#http-status-codes-5xx)

#### respondInternalError

[](#respondinternalerror)

Use this for general server errors **(500)**.

```
Syndra::respondInternalError($message='Internal Error')
```

#### respondNotImplemented

[](#respondnotimplemented)

Use this for HTTP not implemented errors **(501)**.

```
Syndra::respondNotImplemented($message='Not Implemented')
```

### Manipulating the status code

[](#manipulating-the-status-code)

#### setStatusCode

[](#setstatuscode)

Sets status code manually. This method can be chained (combined) with other methods.

```
Syndra::setStatusCode($statusCode)
```

**Example:**

```
Syndra::setStatusCode(200)->respond($data);

```

### Manipulating headers

[](#manipulating-headers)

#### setHeaders

[](#setheaders)

Sets headers on the response. This method can be chained (combined) with other methods.

```
Syndra::setHeaders(array $headers)
```

**Example:**

```
Syndra::setHeaders($headers)->respondWithMessage('Hello World!');

```

Credits
-------

[](#credits)

Many thanks to:

- [@delatbabel](https://github.com/delatbabel) for `notImplemented` method and default message values

###  Health Score

36

—

LowBetter than 82% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity29

Limited adoption so far

Community12

Small or concentrated contributor base

Maturity67

Established project with proven stability

 Bus Factor1

Top contributor holds 85.2% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~71 days

Total

5

Last Release

3679d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/40ea19c312cecdbaa94b6961d083acc981cda402871f0b53b5baa493c0c7e775?d=identicon)[mabasic](/maintainers/mabasic)

---

Top Contributors

[![mabasic](https://avatars.githubusercontent.com/u/1839930?v=4)](https://github.com/mabasic "mabasic (23 commits)")[![delatbabel](https://avatars.githubusercontent.com/u/2335362?v=4)](https://github.com/delatbabel "delatbabel (4 commits)")

---

Tags

apilaravelresponsejsonapilaravel

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/laravelista-syndra/health.svg)

```
[![Health](https://phpackages.com/badges/laravelista-syndra/health.svg)](https://phpackages.com/packages/laravelista-syndra)
```

###  Alternatives

[essa/api-tool-kit

set of tools to build an api with laravel

52680.5k](/packages/essa-api-tool-kit)[resend/resend-laravel

Resend for Laravel

1191.4M6](/packages/resend-resend-laravel)[dragon-code/laravel-json-response

Automatically always return a response in JSON format

1118.6k1](/packages/dragon-code-laravel-json-response)[wayofdev/laravel-symfony-serializer

📦 Laravel wrapper around Symfony Serializer.

2113.6k](/packages/wayofdev-laravel-symfony-serializer)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
