Cut PHP Code Review Time & Bugs into Half with CodeRabbit

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
Battle Ready Laravel

The ultimate guide to auditing, testing, fixing and improving your Laravel applications so you can build better apps faster and with more confidence.

Visit Battle Ready Laravel
Curotec logo

Curotec

World class Laravel experts with GenAI dev skills. LATAM-based, embedded engineers that ship fast, communicate clearly, and elevate your product. No bloat, no BS.

Curotec
Bacancy logo

Bacancy

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

Bacancy
Tinkerwell logo

Tinkerwell

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

Tinkerwell
Cut PHP Code Review Time & Bugs into Half with CodeRabbit logo

Cut PHP Code Review Time & Bugs into Half with CodeRabbit

CodeRabbit is an AI-powered code review tool that specializes in PHP and Laravel, running PHPStan and offering automated PR analysis, security checks, and custom review features while remaining free for open-source projects.

Cut PHP Code Review Time & Bugs into Half with CodeRabbit
Get expert guidance in a few days with a Laravel code review logo

Get expert guidance in a few days with a Laravel code review

Expert code review! Get clear, practical feedback from two Laravel devs with 10+ years of experience helping teams build better apps.

Get expert guidance in a few days with a Laravel code review
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
Harpoon: Next generation time tracking and invoicing logo

Harpoon: Next generation time tracking and invoicing

The next generation time-tracking and billing software that helps your agency plan and forecast a profitable future.

Harpoon: Next generation time tracking and invoicing
Lucky Media logo

Lucky Media

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

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
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Multi-tenant 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

The latest

View all →
Laravel 12.44 Adds HTTP Client afterResponse() Callbacks image

Laravel 12.44 Adds HTTP Client afterResponse() Callbacks

Read article
Handle Nested Data Structures in PHP with the Data Block Package image

Handle Nested Data Structures in PHP with the Data Block Package

Read article
Detect and Clean Up Unchanged Vendor Files with Laravel Vendor Cleanup image

Detect and Clean Up Unchanged Vendor Files with Laravel Vendor Cleanup

Read article
Seamless PropelAuth Integration in Laravel with Earhart image

Seamless PropelAuth Integration in Laravel with Earhart

Read article
Laravel API Route image

Laravel API Route

Read article
Laravel News 2025 Recap image

Laravel News 2025 Recap

Read article