Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Pixelairport's avatar

Laravel API... best way? Maybe with Resource for Errors?

I want to build an api and dont know where to start. I found this packages:

  1. https://github.com/timacdonald/json-api => This has no error responses. Seems it only make structured resources.

  2. https://github.com/cloudcreativity/laravel-json-api => Seems to have a bit more. But I'm not sure, if it is still maintained and if it is not to much.

Now I think about doing something like a ErrorResponseResource in my resource directory. Would this be a good idea? But then I response with 200. I will response with 500 for example. Can I say to my Resource which extends JsonResource something like always response with 500?

I hope somebody can help me where to start and how to begin. thx

0 likes
1 reply
LaryAI's avatar
Level 58

For building APIs in Laravel, you can use Laravel's built-in resource classes. These classes allow you to transform your models and model collections into JSON responses. You can also use Laravel's exception handling to handle errors and return appropriate responses.

Here's an example of how you can use Laravel's resource classes and exception handling to build an API:

  1. Create a new Laravel project:
laravel new my-api
  1. Create a new controller for your API:
php artisan make:controller ApiController
  1. In your ApiController, define methods for each endpoint of your API. For example:
use App\Http\Resources\UserResource;
use App\Models\User;
use Illuminate\Http\Request;

class ApiController extends Controller
{
    public function getUsers()
    {
        $users = User::all();
        return UserResource::collection($users);
    }

    public function getUser(Request $request, $id)
    {
        $user = User::find($id);
        if (!$user) {
            throw new \Exception('User not found', 404);
        }
        return new UserResource($user);
    }
}
  1. Create a resource class for your model. For example, if you have a User model, create a UserResource class:
php artisan make:resource UserResource
  1. In your UserResource class, define how your model should be transformed into a JSON response. For example:
use Illuminate\Http\Resources\Json\JsonResource;

class UserResource extends JsonResource
{
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'email' => $this->email,
        ];
    }
}
  1. In your App\Exceptions\Handler class, define how exceptions should be handled. For example:
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Http\JsonResponse;

class Handler extends ExceptionHandler
{
    protected function prepareJsonResponse($request, Throwable $e)
    {
        return new JsonResponse([
            'error' => $e->getMessage(),
        ], $e->getStatusCode());
    }
}
  1. Finally, define your API routes in routes/api.php. For example:
Route::get('/users', 'ApiController@getUsers');
Route::get('/users/{id}', 'ApiController@getUser');

Now you can start your Laravel server and test your API:

php artisan serve

To test error responses, you can make a request to an endpoint that doesn't exist:

curl http://localhost:8000/api/non-existent-endpoint

This should return a JSON response with an error message and a 404 status code.

Note that this is just a basic example of how you can build an API in Laravel. Depending on your requirements, you may need to add more features such as authentication, pagination, filtering, etc.

1 like

Please or to participate in this conversation.