Building REST APIs with Laravel Orion

Tutorials

December 11th, 2020

orion.png

Have you noticed, that when building an API, you often keep writing the same code over and over again? You create a controller for [name your entity here] with methods for listing, creating, showing, updating, and deleting that [entity]. Then you create another controller, and it happens again, and again. Then you need to write some custom methods (endpoints) just to support updating a relation or a field on the pivot table? Sounds familiar, isn’t it?

Over the past year I was working on a Laravel package that does exactly that – abstracts these patterns, so you could focus on what really matters – building your application.
Laravel Orion allows you to build fully-featured REST APIs in a matter of minutes by providing common endpoints for CRUD operations, working with soft deletable models, and performing a comprehensive search. It works hand in hand with Laravel solutions like Requests for handling validation, Policies for handling authorization, and Resources for transforming responses.

The best part? It works for both models and their relations! Yep, all relations, including the most complex ones, such as belongsToMany and morphToMany are supported. Meaning, you can, for example, sync models on a relation via an endpoint that is made available just by writing 2 lines of the code in a controller.

Let’s take a look at some examples.

Model Resources

Let’s assume you have a model Post that represents a blog post and you would like to manage it via REST API.

With Laravel Orion it can be accomplished in 3 simple steps:

First, create the PostsController and extend it from OrionHttpControllersController

1<?php
2 
3namespace App\Http\Controllers\Api;
4 
5use App\Models\Post;
6use Orion\Http\Controllers\Controller;
7 
8class PostsController extends Controller
9{
10 
11}

Then define the $model property and set it to the fully-qualified model class name. The complete controller should look like this:

1<?php
2 
3namespace App\Http\Controllers\Api;
4 
5use Orion\Http\Controllers\Controller;
6 
7class PostsController extends Controller
8{
9 /**
10 * Fully-qualified model class name
11 */
12 protected $model = Post::class; // or "AppModelsPost"
13}

Finally, register the routes in api.php by calling Orion::resource

1<?php
2 
3use Illuminate\Support\Facades\Route;
4use Orion\Facades\Orion;
5use App\Http\Controllers\PostsController;
6 
7Route::group(['as' => 'api.'], function() {
8 Orion::resource('posts', PostsController::class);
9});

Done :tada: Now you can create, list, search, view, update, and delete blog posts via REST API. Try to create a post via (POST) https://<your app url>/api/posts endpoint :wink:

You can also take a look at all available endpoints by running php artisan route:list command.

Relation Resources

Working with related resources is very similar to model resources with two minor differences:

  • Relation resource controller must extend Orion\Http\Controllers\RelationController
  • We need to define an additional property $relation on the controller to tell Laravel Orion what relation on the model it should work with.

First, create the controller and extend it from Orion\Http\Controllers\RelationController

1<?php
2 
3namespace App\Http\Controllers\Api;
4 
5use App\Models\Post;
6use Orion\Http\Controllers\RelationController;
7 
8class PostCommentsController extends RelationController
9{
10}

Then define $model and $relation properties. The complete controller should look like this:

1<?php
2 
3namespace App\Http\Controllers\Api;
4 
5use App\Models\Post;
6use Orion\Http\Controllers\RelationController;
7 
8class PostCommentsController extends RelationController
9{
10 /**
11 * Fully-qualified model class name
12 */
13 protected $model = Post::class; // or "App\Models\Post"
14 
15 /**
16 * Name of the relationship as it is defined on the Post model
17 */
18 protected $relation = 'comments';
19}

Finally, register the routes in api.php by calling Orion::morphToManyResource.

1<?php
2 
3use Illuminate\Support\Facades\Route;
4use Orion\Facades\Orion;
5use App\Http\Controllers\PostsController;
6use App\Http\Controllers\PostCommentsController;
7 
8Route::group(['as' => 'api.'], function() {
9 Orion::resource('posts', PostsController::class);
10 Orion::morphToManyResource('posts', 'comments', PostCommentsController::class);
11});

Now you can manage posts and their comments via REST API

Final Notes

Policies

Make sure to have policy created and registered for the model you are exposing via the API or consider using DisableAuthorization trait (only for local testing) to avoid getting a 403 error if the policy is not registered or incorrect.

Usage with Sanctum or other Auth guards

By default, api guard is used to resolve the currently authenticated user for authorization.

However, you can change the way the user is resolved by overriding resolveUser method on a controller.

1<br></br>namespace App\Http\Controllers\Api;
2 
3use Orion\Http\Controllers\Controller;
4use App\Models\Post;
5 
6class PostsController extends Controller
7{
8 /**
9 * @var string $model
10 */
11 protected $model = Post::class;
12 
13 /**
14 * Retrieves currently authenticated user based on the guard.
15 *
16 * @return \Illuminate\Contracts\Auth\Authenticatable|null
17 */
18 public function resolveUser()
19 {
20 return Auth::guard('sanctum')->user();
21 }
22}

What’s next?

It has been a crazy year for all of us, but it should not stop us from innovating and moving forward! That being said, here is a quick overview of what is coming to Laravel Orion:

  • Typescript SDK to make integration with frontend simple and standardized
  • Full support for JSON fields
  • Enhanced batch operations
  • Testing utilities

Hope you stay safe and have a great week!