Building REST APIs with Laravel Orion

Published on by

Building REST APIs with Laravel Orion image

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

<?php
 
namespace App\Http\Controllers\Api;
 
use App\Models\Post;
use Orion\Http\Controllers\Controller;
 
class PostsController extends Controller
{
 
}

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

<?php
 
namespace App\Http\Controllers\Api;
 
use Orion\Http\Controllers\Controller;
 
class PostsController extends Controller
{
/**
* Fully-qualified model class name
*/
protected $model = Post::class; // or "AppModelsPost"
}

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

<?php
 
use Illuminate\Support\Facades\Route;
use Orion\Facades\Orion;
use App\Http\Controllers\PostsController;
 
Route::group(['as' => 'api.'], function() {
Orion::resource('posts', PostsController::class);
});

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

<?php
 
namespace App\Http\Controllers\Api;
 
use App\Models\Post;
use Orion\Http\Controllers\RelationController;
 
class PostCommentsController extends RelationController
{
}

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

<?php
 
namespace App\Http\Controllers\Api;
 
use App\Models\Post;
use Orion\Http\Controllers\RelationController;
 
class PostCommentsController extends RelationController
{
/**
* Fully-qualified model class name
*/
protected $model = Post::class; // or "App\Models\Post"
 
/**
* Name of the relationship as it is defined on the Post model
*/
protected $relation = 'comments';
}

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

<?php
 
use Illuminate\Support\Facades\Route;
use Orion\Facades\Orion;
use App\Http\Controllers\PostsController;
use App\Http\Controllers\PostCommentsController;
 
Route::group(['as' => 'api.'], function() {
Orion::resource('posts', PostsController::class);
Orion::morphToManyResource('posts', 'comments', PostCommentsController::class);
});

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.

<br></br>namespace App\Http\Controllers\Api;
 
use Orion\Http\Controllers\Controller;
use App\Models\Post;
 
class PostsController extends Controller
{
/**
* @var string $model
*/
protected $model = Post::class;
 
/**
* Retrieves currently authenticated user based on the guard.
*
* @return \Illuminate\Contracts\Auth\Authenticatable|null
*/
public function resolveUser()
{
return Auth::guard('sanctum')->user();
}
}

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!

Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

image
Laravel Forge

Easily create and manage your servers and deploy your Laravel applications in seconds.

Visit Laravel Forge
Laravel Forge logo

Laravel Forge

Easily create and manage your servers and deploy your Laravel applications in seconds.

Laravel Forge
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
No Compromises logo

No Compromises

Joel and Aaron, the two seasoned devs from the No Compromises podcast, are now available to hire for your Laravel project. ⬧ Flat rate of $7500/mo. ⬧ No lengthy sales process. ⬧ No contracts. ⬧ 100% money back guarantee.

No Compromises
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
Bacancy logo

Bacancy

Supercharge your project with a seasoned Laravel developer with 4-6 years of experience for just $2500/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
LoadForge logo

LoadForge

Easy, affordable load testing and stress tests for websites, APIs and databases.

LoadForge
Paragraph logo

Paragraph

Manage your Laravel app as if it was a CMS – edit any text on any page or in any email without touching Blade or language files.

Paragraph
Lucky Media logo

Lucky Media

Bespoke software solutions built for your business. We ♥ Laravel

Lucky Media
Lunar: Laravel E-Commerce logo

Lunar: Laravel E-Commerce

E-Commerce for Laravel. An open-source package that brings the power of modern headless e-commerce functionality to Laravel.

Lunar: Laravel E-Commerce
DocuWriter.ai logo

DocuWriter.ai

Save hours of manually writing Code Documentation, Comments & DocBlocks, Test suites and Refactoring.

DocuWriter.ai
LaraJobs logo

LaraJobs

The official Laravel job board

LaraJobs
All Green logo

All Green

All Green is a SaaS test runner that can execute your whole Laravel test suite in mere seconds so that you don't get blocked – you get feedback almost instantly and you can deploy to production very quickly.

All Green
Larafast: Laravel SaaS Starter Kit logo

Larafast: Laravel SaaS Starter Kit

Larafast is a Laravel SaaS Starter Kit with ready-to-go features for Payments, Auth, Admin, Blog, SEO, and beautiful themes. Available with VILT and TALL stacks.

Larafast: Laravel SaaS Starter Kit
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit
Rector logo

Rector

Your partner for seamless Laravel upgrades, cutting costs, and accelerating innovation for successful companies

Rector

The latest

View all →
The Random package generates cryptographically secure random values image

The Random package generates cryptographically secure random values

Read article
Automatic Blade Formatting on Save in PhpStorm image

Automatic Blade Formatting on Save in PhpStorm

Read article
PhpStorm 2024.1 Is Released With a Integrated Terminal, Local AI Code Completion, and More image

PhpStorm 2024.1 Is Released With a Integrated Terminal, Local AI Code Completion, and More

Read article
Laravel Prompts Adds a Multi-line Textarea Input, Laravel 11.3 Released image

Laravel Prompts Adds a Multi-line Textarea Input, Laravel 11.3 Released

Read article
Bartender Is an Opinionated Way to Authenticate Users Using Laravel Socialite image

Bartender Is an Opinionated Way to Authenticate Users Using Laravel Socialite

Read article
Jeffrey Way's PhpStorm Setup in 2024 image

Jeffrey Way's PhpStorm Setup in 2024

Read article