PHPackages                             laravue2/rest-api - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [API Development](/categories/api)
4. /
5. laravue2/rest-api

ActiveLibrary[API Development](/categories/api)

laravue2/rest-api
=================

RestAPI plugin

v13.0.3(3w ago)015↓66.7%MITPHP

Since Apr 8Pushed 3w agoCompare

[ Source](https://github.com/Pvngu/rest-api)[ Packagist](https://packagist.org/packages/laravue2/rest-api)[ RSS](/packages/laravue2-rest-api/feed)WikiDiscussions main Synced 2w ago

READMEChangelogDependencies (2)Versions (5)Used By (0)

Laravel RestAPI Package (`laravue2/rest-api`)
=============================================

[](#laravel-restapi-package-laravue2rest-api)

A powerful and flexible package for Laravel that automates the creation of robust RESTful APIs. It facilitates advanced filtering, dynamic field selection, relationship eager loading and counting, pagination, API versioning, and Hashids integration out-of-the-box with minimal configuration.

---

⚡ Key Features
--------------

[](#-key-features)

- **Ready-to-Use CRUD Controllers**: Automated and customizable `index`, `show`, `store`, `update`, and `destroy` endpoints.
- **SQL-like Advanced Filtering**: Compare and filter query results directly from the URL, supporting complex logical queries (`and`, `or`, and parenthesis `()`).
- **Dynamic Field Selection (`fields`)**: Allows clients to specify exactly which columns and relations (including nested relations) to return in the JSON payload.
- **Inline Limits on Relations**: Restrict and paginate child relations (e.g., `HasMany`, `BelongsToMany`) inline directly via the `fields` parameter.
- **Dynamic Relation Counting (`with_count`)**: Eagerly count related records on demand using a simple URL query parameter.
- **Dedicated Relation Endpoints**: Automatic sub-routing for querying specific relation collections directly (`GET /resource/{id}/{relation}`).
- **Controller Hook Methods**: Leverage lifecycle hooks such as `storing`, `stored`, `updating`, `updated`, etc., to inject custom business logic.
- **Native Hashids Integration**: Automatically encodes and decodes model IDs to protect database primary keys from enumeration attacks.
- **CORS &amp; API Versioning**: Global CORS headers control and a custom router setup with automatic version prefixing (e.g., `api/v1`).

---

⚙️ Installation &amp; Configuration
-----------------------------------

[](#️-installation--configuration)

### 1. Register the Service Provider

[](#1-register-the-service-provider)

If you are using an older version of Laravel without package auto-discovery, add the Service Provider in your `config/app.php` file:

```
'providers' => [
    // ...
    Laravue2\RestAPI\Providers\ApiServiceProvider::class,
];
```

### 2. Publish the Configuration File

[](#2-publish-the-configuration-file)

Run the following command to publish the package configuration to `config/api.php`:

```
php artisan vendor:publish --provider="Laravue2\RestAPI\Providers\ApiServiceProvider"
```

The configuration file contains the following keys:

- `defaultLimit`: Default pagination size when no limit is provided (10).
- `maxLimit`: Maximum allowed pagination size to prevent database overload (1000).
- `cors`: Enable or disable CORS response headers (true/false).
- `cors_headers`: List of headers allowed in CORS preflight requests.
- `prefix`: Global prefix for all API routes (e.g., `api`).
- `default_version`: Default fallback API version (e.g., `v1`). Set `null` to disable versions.

---

🏗️ Basic Usage Guide
--------------------

[](#️-basic-usage-guide)

### 1. Define the Model (`ApiModel`)

[](#1-define-the-model-apimodel)

Your Eloquent models must extend `Laravue2\RestAPI\ApiModel` instead of Laravel's base Model class:

```
namespace App\Models;

use Laravue2\RestAPI\ApiModel;

class Product extends ApiModel
{
    // Database columns to return by default if the "fields" parameter is omitted
    protected $default = ['id', 'name', 'price', 'status'];

    // Database columns allowed to be filtered in URL query parameters
    protected $filterable = ['id', 'name', 'price', 'status', 'category_id'];

    // Standard Eloquent relationship
    public function category()
    {
        return $this->belongsTo(Category::class);
    }
}
```

### 2. Define the Controller (`ApiController`)

[](#2-define-the-controller-apicontroller)

Your controllers must extend `Laravue2\RestAPI\ApiController`. Simply define the target model property:

```
namespace App\Http\Controllers\Api;

use App\Models\Product;
use Laravue2\RestAPI\ApiController;
use App\Http\Requests\StoreProductRequest;
use App\Http\Requests\UpdateProductRequest;

class ProductController extends ApiController
{
    protected $model = Product::class;

    // Optional: Attach FormRequest classes for validation during CRUD actions
    protected $storeRequest = StoreProductRequest::class;
    protected $updateRequest = UpdateProductRequest::class;
}
```

### 3. Register the Routes

[](#3-register-the-routes)

The package provides an `ApiRouter` helper that automatically registers restful resource endpoints along with a relation helper endpoint.

In your `routes/api.php` file:

```
use Laravue2\RestAPI\Facades\ApiRoute;

// Define versioned routes
ApiRoute::group(['namespace' => 'App\Http\Controllers\Api'], function () {
    ApiRoute::resource('products', 'ProductController');
}
```

This registers the following routes under the hood:

- `GET /api/v1/products` (index)
- `POST /api/v1/products` (store)
- `GET /api/v1/products/{id}` (show)
- `PUT /api/v1/products/{id}` (update)
- `DELETE /api/v1/products/{id}` (destroy)
- `GET /api/v1/products/{id}/{relation}` (relation - Endpoint for querying child relationship lists)

---

🔍 Consuming the API (URL Query Parameters)
------------------------------------------

[](#-consuming-the-api-url-query-parameters)

Clients can customize response structures dynamically using query strings in the URL.

### A. Dynamic Field Selection &amp; Relations (`fields`)

[](#a-dynamic-field-selection--relations-fields)

Select specific table columns to return, and eagerly load nested relationships using curly braces `{}`.

- **Basic Example:** Retrieve only `id` and `name`: ```
    GET /api/v1/products?fields=id,name
    ```
- **With Eager Loading:** Retrieve products and their categories: ```
    GET /api/v1/products?fields=id,name,category{id,name}
    ```
- **Multi-level Eager Loading:** Retrieve product with category and warehouse detail: ```
    GET /api/v1/products?fields=id,name,category{id,name},warehouse{id,name}
    ```

#### Inline Limits and Offsets on Child Relations

[](#inline-limits-and-offsets-on-child-relations)

You can control the pagination and ordering of a `HasMany` or `BelongsToMany` relation directly inside the `fields` query string:

```
GET /api/v1/suppliers?fields=id,name,supplied_products.limit(5).offset(0).order(chronological){id,name}
```

---

### B. Advanced Filtering (`filters`)

[](#b-advanced-filtering-filters)

Construct complex search queries using the `filters` URL parameter.

**Supported Operators:**

- `eq` (Equals / `=`): `name eq "Laptop"`
- `ne` (Not Equals / `!=`): `status ne "disabled"`
- `gt` (Greater Than / `>`): `price gt 150`
- `ge` (Greater or Equal / `>=`): `price ge 100`
- `lt` (Less Than / ` $this->xid,
        'name' => $this->name,

        // This will only be present in the final JSON response when requested in the URL
        'supplied_products_count' => $this->whenCounted('supplied_products'),
    ];
}
```

---

### F. Dedicated Relation Endpoints

[](#f-dedicated-relation-endpoints)

If you do not need information about the parent resource and only want to fetch its related items, query the relationship endpoint directly:

```
GET /api/v1/suppliers/M6q8Pvqz/supplied_products?limit=10&offset=0
```

*(This returns the collection of products associated with the supplier whose decoded ID is `M6q8Pvqz`).*

---

🪝 Controller Lifecycle Hooks
----------------------------

[](#-controller-lifecycle-hooks)

You can intercept actions within your custom controllers by overriding any of the following lifecycle hook methods:

```
class ProductController extends ApiController
{
    protected $model = Product::class;

    // Called before the model is saved (Creation)
    protected function storing($object)
    {
        $object->created_by = auth()->id();
        return $object;
    }

    // Called after the model has been saved (Creation)
    protected function stored($object)
    {
        // Trigger emails, push notifications, log actions, etc.
    }

    // Called before the model is updated
    protected function updating($object)
    {
        return $object;
    }

    // Called after the model has been updated
    protected function updated($object)
    {
        // ...
    }

    // Called before the model is deleted
    protected function destroying($object)
    {
        return $object;
    }

    // Called after the model has been deleted
    protected function destroyed($object)
    {
        // ...
    }
}
```

---

🔒 Security &amp; Hashids Integration
------------------------------------

[](#-security--hashids-integration)

The package integrates `Vinkla\Hashids` to prevent database auto-increment ID exposure in the API layer:

1. **CRUD Resource Routes**: The controller automatically decodes incoming `{id}` hashids before querying records in `show`, `update`, and `destroy` endpoints.
2. **Hashable Filter Fields (`hashable`)**: If you filter on primary keys or foreign keys, specify the column names in the `hashable` parameter. The parser decodes these hashids to their numeric database counterparts automatically before executing queries: ```
    GET /api/v1/products?filters=category_id eq "M6q8Pvqz"&hashable=category_id
    ```

    *(The query parser will decode `M6q8Pvqz` to the integer ID to build the SQL query).*

###  Health Score

38

—

LowBetter than 83% of packages

Maintenance94

Actively maintained with recent releases

Popularity8

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity37

Early-stage or recently created project

 Bus Factor1

Top contributor holds 64% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~17 days

Total

4

Last Release

26d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/0b822060d1f695101d1ad4a5a99a8659374e9f17f62941b1a5559c1c215629b8?d=identicon)[Pvngu](/maintainers/Pvngu)

---

Top Contributors

[![rkumwt](https://avatars.githubusercontent.com/u/21355037?v=4)](https://github.com/rkumwt "rkumwt (16 commits)")[![Pvngu](https://avatars.githubusercontent.com/u/144563688?v=4)](https://github.com/Pvngu "Pvngu (9 commits)")

### Embed Badge

![Health badge](/badges/laravue2-rest-api/health.svg)

```
[![Health](https://phpackages.com/badges/laravue2-rest-api/health.svg)](https://phpackages.com/packages/laravue2-rest-api)
```

###  Alternatives

[statamic/cms

The Statamic CMS Core Package

4.8k3.5M916](/packages/statamic-cms)[darkaonline/l5-swagger

OpenApi or Swagger integration to Laravel

2.9k36.4M126](/packages/darkaonline-l5-swagger)[knuckleswtf/scribe

Generate API documentation for humans from your Laravel codebase.✍

2.3k13.5M59](/packages/knuckleswtf-scribe)[mozex/anthropic-laravel

Laravel integration for the Anthropic API: facade, config publishing, install command, testing fakes, messages, streaming, tool use, thinking, and batches.

72287.1k1](/packages/mozex-anthropic-laravel)[justbetter/laravel-magento-client

A client to interact with Magento

49108.7k14](/packages/justbetter-laravel-magento-client)[scriptdevelop/whatsapp-manager

Paquete para manejo de WhatsApp Business API en Laravel

783.5k](/packages/scriptdevelop-whatsapp-manager)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
