Programming
We provide developers and engineers the guides and tutorials they...
Search
We provide developers and engineers the guides and tutorials they...
Content is king. It's not just about how you're going to write, b...
Looking for an engaging connection with thousands of other people...
Learn how to streamline your API responses with Laravel Responsables. Our guide provides tips for standardizing your code and improving your development workflow.
If you're building an API in Laravel, it is likely that you should be outputing responses to display success or error messages. What if you can standardize these responses and you don't need to repeat json responses in every single controller. Luckily, now Laravel has a Responsable interface which simply allows to convert an object into a response.
Previously, we had to write separate responses for all endpoints, for example, below is the lesson creation endpoint, where we're getting title from the request from the user.
Also Read: Laravel Livewire comments
Endpoint: {{base_url}}/api/lessons
try {
$lesson = App\Models\Lesson::create($request->title);
} catch (Throwable $e) {
return response()->json([
'message' => 'failed to create lesson'
]);
}
return response()->json([
'message' => 'lesson created successfully'
]);With Laravel Responsable, all API responses can be standardised and will use the similar sort of success or error json responses. To achieve this, you can simply create two Response classes for success and error, and can return those classes from anywhere from the app.
Also Read: Deploy Laravel App with Envoy
<?php
namespace App\Http\Responses;
use Illuminate\Contracts\Support\Responsable;
use Illuminate\Http\Response;
class ApiSuccessResponse implements Responsable
{
/**
* @param mixed $data
* @param array $metaData
* @param int $code
* @param array $headers
*/
public function __construct(
protected mixed $data,
protected array $metaData,
protected int $code = Response::HTTP_OK,
protected array $headers = []
) {
}
/**
* @param $request
* @return \Illuminate\Http\JsonResponse|\Symfony\Component\HttpFoundation\Response
*/
public function toResponse($request)
{
return response()->json([
'data' => $this->data,
'metadata' => $this->metaData
], $this->code, $this->headers);
}
}
<?php
namespace App\Http\Responses;
use Illuminate\Contracts\Support\Responsable;
use Illuminate\Http\Response;
use Throwable;
class ApiErrorResponse implements Responsable
{
/**
* @param Throwable $e
* @param string $message
* @param int $code
* @param array $headers
*/
public function __construct(
protected Throwable $e,
protected string $message,
protected int $code = Response::HTTP_INTERNAL_SERVER_ERROR,
protected array $headers = []
) {
}
/**
* @param $request
* @return \Illuminate\Http\JsonResponse|\Symfony\Component\HttpFoundation\Response
*/
public function toResponse($request)
{
$response = ['message' => $this->message];
if ($this->e && config('app.debug')) {
$response['debug'] = [
'message' => $this->e->getMessage(),
'file' => $this->e->getFile(),
'line' => $this->e->getLine(),
'trace' => $this->e->getTrace()
];
}
return \response()->json($response, $this->code, $this->headers);
}
}
We can simply and standardise our API responses using the above classes, you can now simply return those classes and pass in the params as you'd like per your API needs.
Also Read: Code formatting with Laravel Pint
try {
$lesson = App\Models\Lesson::create($request->title);
} catch (Throwable $e) {
return new \App\Http\Responses\ApiErrorResponse($e, 'failed to create lesson', 500);
}
return new \App\Http\Responses\ApiSuccessResponse($lesson,
['message' => 'lesson created successfully'],
201
); Also Read: One to Many Polymorphic Relations in Laravel