PHPackages                             jaikumar0101/laravel-inputbag - 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. jaikumar0101/laravel-inputbag

ActiveLaravel-package[API Development](/categories/api)

jaikumar0101/laravel-inputbag
=============================

Fluent request input builder for Laravel

v1.0.5(3mo ago)110MITPHPPHP ^8.2CI passing

Since Jan 25Pushed 3mo agoCompare

[ Source](https://github.com/Jaikumar0101/laravel-input-bag-request)[ Packagist](https://packagist.org/packages/jaikumar0101/laravel-inputbag)[ Docs](https://github.com/jaikumar0101/laravel-inputbag)[ RSS](/packages/jaikumar0101-laravel-inputbag/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (6)Dependencies (3)Versions (7)Used By (0)

Laravel InputBag
================

[](#laravel-inputbag)

[![Latest Version on Packagist](https://camo.githubusercontent.com/a57969e6ececfba6e357d8351e03bda339ea17cbe1dd1f5b439efda027882d36/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6a61696b756d6172303130312f6c61726176656c2d696e7075746261672e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/jaikumar0101/laravel-inputbag)[![Total Downloads](https://camo.githubusercontent.com/69232a33d10ff500ff0fe07fdff026d5bb2115c37410b5871e0ea5d0dd5347de/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6a61696b756d6172303130312f6c61726176656c2d696e7075746261672e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/jaikumar0101/laravel-inputbag)[![License](https://camo.githubusercontent.com/b0f8c7eb063d75a1b821c0a02fd3f034b6a6e398455139740bd2c3f93895485a/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f6a61696b756d6172303130312f6c61726176656c2d696e7075746261672e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/jaikumar0101/laravel-inputbag)

A fluent builder for standardizing request inputs (search, pagination, sorting) in Laravel applications. Simplify your controller logic and maintain consistent API responses across your application.

Features
--------

[](#features)

- 🔍 **Standardized Input Handling** - Automatically process search, pagination, and sorting parameters
- 🎯 **Fluent API** - Chain methods for clean and readable code
- ⚙️ **Configurable Defaults** - Set global defaults for pagination and sorting
- 🔧 **Custom Mappings** - Map custom request fields with ease
- 📦 **Type Safety** - Return as array or collection based on your needs
- 🚀 **Zero Configuration** - Works out of the box with sensible defaults
- ✨ **Auto-Load Custom Fields** - Define common fields once in config, use everywhere

Requirements
------------

[](#requirements)

- PHP 8.2 or higher
- Laravel 11.x or 12.x

Installation
------------

[](#installation)

Install the package via Composer:

```
composer require jaikumar0101/laravel-inputbag
```

### Publish Configuration (Optional)

[](#publish-configuration-optional)

Publish the configuration file to customize default values:

```
php artisan vendor:publish --tag="inputbag-config"
```

This will create a `config/inputbag.php` file where you can customize defaults such as `per_page`, `sort_by`, `order_by`, and define custom fields.

Quick Start
-----------

[](#quick-start)

### Basic Usage

[](#basic-usage)

```
use Jaikumar0101\LaravelInputbag\InputBag;
use Illuminate\Http\Request;

class ProductController extends Controller
{
    public function index(Request $request)
    {
        $inputs = InputBag::make($request)->standard()->toArray();

        $products = Product::when($inputs['search'], fn($q) =>
                        $q->where('name', 'like', '%' . $inputs['search'] . '%'))
                    ->orderBy($inputs['sort_by'], $inputs['order_by'])
                    ->paginate($inputs['per_page']);

        return response()->json($products);
    }
}
```

### Using Facade

[](#using-facade)

```
use Jaikumar0101\LaravelInputbag\Facades\InputBag;

class ProductController extends Controller
{
    public function index()
    {
        // Request is automatically injected when using facade
        $inputs = InputBag::standard()->toArray();

        $products = Product::when($inputs['search'], fn($q) =>
                        $q->where('name', 'like', '%' . $inputs['search'] . '%'))
                    ->orderBy($inputs['sort_by'], $inputs['order_by'])
                    ->paginate($inputs['per_page']);

        return response()->json($products);
    }
}
```

Standard Inputs
---------------

[](#standard-inputs)

The `standard()` method processes the following request parameters:

ParameterDefault ValueDescription`search``null`Search query string`page``1`Current page number`per_page``15`Number of items per page`sort_by``id`Column to sort by`order_by``desc`Sort direction (`asc` or `desc`)Custom Fields
-------------

[](#custom-fields)

### Method 1: Manual Mapping (Per Controller)

[](#method-1-manual-mapping-per-controller)

Map custom request fields on a per-controller basis:

```
use Jaikumar0101\LaravelInputbag\InputBag;
use Illuminate\Http\Request;

class ProductController extends Controller
{
    public function index(Request $request)
    {
        $inputs = InputBag::make($request)
            ->set('status', 'filter_status', 'active')
            ->set('category', 'category_id')
            ->set('min_price', 'price_min', 0)
            ->set('max_price', 'price_max', 999999)
            ->standard()
            ->toArray();

        // Use $inputs array in your query
    }
}
```

### Method 2: Auto-Load from Config (Application-Wide) ⭐ NEW

[](#method-2-auto-load-from-config-application-wide--new)

Define custom fields once in your config file, and they'll be automatically included in all controllers using `standard()`:

**1. Configure in `config/inputbag.php`:**

```
return [
    'defaults' => [
        'per_page' => 15,
        'sort_by' => 'id',
        'order_by' => 'desc',
    ],

    'custom_fields' => [
        // Simple syntax: 'key' => 'request_parameter'
        'status' => 'status',

        // Advanced syntax with default value
        'category' => [
            'request_key' => 'category_id',
            'default' => null
        ],

        'featured' => [
            'request_key' => 'featured',
            'default' => false
        ],

        'min_price' => [
            'request_key' => 'price_min',
            'default' => 0
        ],

        'max_price' => [
            'request_key' => 'price_max',
            'default' => 999999
        ],
    ],
];
```

**2. Use in any controller:**

```
class ProductController extends Controller
{
    public function index(Request $request)
    {
        // One line - all custom fields automatically loaded!
        $inputs = InputBag::make($request)->standard()->toArray();

        // Available automatically:
        // $inputs['search'], $inputs['page'], $inputs['per_page']
        // $inputs['sort_by'], $inputs['order_by']
        // $inputs['status'], $inputs['category'], $inputs['featured']
        // $inputs['min_price'], $inputs['max_price']

        $products = Product::query()
            ->when($inputs['search'], fn($q) =>
                $q->where('name', 'like', '%' . $inputs['search'] . '%'))
            ->when($inputs['category'], fn($q) =>
                $q->where('category_id', $inputs['category']))
            ->when($inputs['status'], fn($q) =>
                $q->where('status', $inputs['status']))
            ->when($inputs['featured'], fn($q) =>
                $q->where('featured', true))
            ->whereBetween('price', [$inputs['min_price'], $inputs['max_price']])
            ->orderBy($inputs['sort_by'], $inputs['order_by'])
            ->paginate($inputs['per_page']);

        return response()->json($products);
    }
}
```

**Benefits of Config-Based Custom Fields:**

- ✅ Define once, use everywhere
- ✅ Consistent across all controllers
- ✅ Easy to maintain
- ✅ Environment-specific defaults

### Combining Both Methods

[](#combining-both-methods)

You can combine config-based fields with manual fields:

```
// Config has: status, category
$inputs = InputBag::make($request)
    ->set('special_filter', 'special_param', 'default')  // Add extra field
    ->standard()  // Loads standard + config fields
    ->toArray();

// Result: standard + config + manual fields
```

Advanced Example
----------------

[](#advanced-example)

### E-commerce Product Listing (Array Access)

[](#e-commerce-product-listing-array-access)

```
use Jaikumar0101\LaravelInputbag\InputBag;
use Illuminate\Http\Request;

class ProductController extends Controller
{
    public function index(Request $request)
    {
        $inputs = InputBag::make($request)
            ->set('brand', 'brand_id')
            ->set('in_stock', 'in_stock')
            ->standard()  // Also loads fields from config
            ->toArray();

        $products = Product::query()
            ->when($inputs['search'], function ($query) use ($inputs) {
                $query->where('name', 'like', '%' . $inputs['search'] . '%')
                      ->orWhere('description', 'like', '%' . $inputs['search'] . '%');
            })
            ->when($inputs['category'], fn($q) =>
                $q->where('category_id', $inputs['category']))
            ->when($inputs['brand'], fn($q) =>
                $q->where('brand_id', $inputs['brand']))
            ->when($inputs['status'], fn($q) =>
                $q->where('status', $inputs['status']))
            ->when($inputs['in_stock'], fn($q) =>
                $q->where('stock', '>', 0))
            ->when($inputs['featured'], fn($q) =>
                $q->where('featured', true))
            ->whereBetween('price', [$inputs['min_price'], $inputs['max_price']])
            ->orderBy($inputs['sort_by'], $inputs['order_by'])
            ->paginate($inputs['per_page']);

        return response()->json($products);
    }
}
```

### E-commerce Product Listing (Collection Access)

[](#e-commerce-product-listing-collection-access)

```
use Jaikumar0101\LaravelInputbag\InputBag;
use Illuminate\Http\Request;

class ProductController extends Controller
{
    public function index(Request $request)
    {
        $inputs = InputBag::make($request)
            ->set('brand', 'brand_id')
            ->set('in_stock', 'in_stock')
            ->standard()
            ->toCollection();  // Returns Collection!

        $products = Product::query()
            ->when($inputs->get('search'), function ($query) use ($inputs) {
                $query->where('name', 'like', '%' . $inputs->get('search') . '%')
                      ->orWhere('description', 'like', '%' . $inputs->get('search') . '%');
            })
            ->when($inputs->get('category'), fn($q) =>
                $q->where('category_id', $inputs->get('category')))
            ->when($inputs->get('brand'), fn($q) =>
                $q->where('brand_id', $inputs->get('brand')))
            ->when($inputs->get('status'), fn($q) =>
                $q->where('status', $inputs->get('status')))
            ->when($inputs->get('in_stock'), fn($q) =>
                $q->where('stock', '>', 0))
            ->when($inputs->get('featured'), fn($q) =>
                $q->where('featured', true))
            ->whereBetween('price', [
                $inputs->get('min_price', 0),
                $inputs->get('max_price', 999999)
            ])
            ->orderBy($inputs->get('sort_by', 'id'), $inputs->get('order_by', 'desc'))
            ->paginate($inputs->get('per_page', 15));

        return response()->json($products);
    }
}
```

### Using Collection Methods for Advanced Filtering

[](#using-collection-methods-for-advanced-filtering)

```
use Jaikumar0101\LaravelInputbag\InputBag;
use Illuminate\Http\Request;

class ProductController extends Controller
{
    public function index(Request $request)
    {
        $inputs = InputBag::make($request)->standard()->toCollection();

        // Get only non-null filters
        $activeFilters = $inputs->filter(fn($value) => !is_null($value))
                                ->except(['page', 'per_page', 'sort_by', 'order_by']);

        // Build query dynamically
        $query = Product::query();

        // Apply search
        if ($inputs->has('search') && $inputs->get('search')) {
            $query->where('name', 'like', '%' . $inputs->get('search') . '%');
        }

        // Apply all active filters
        foreach ($activeFilters as $key => $value) {
            match($key) {
                'category' => $query->where('category_id', $value),
                'brand' => $query->where('brand_id', $value),
                'status' => $query->where('status', $value),
                'featured' => $query->where('featured', true),
                'in_stock' => $query->where('stock', '>', 0),
                default => null
            };
        }

        // Price range
        if ($inputs->has('min_price') || $inputs->has('max_price')) {
            $query->whereBetween('price', [
                $inputs->get('min_price', 0),
                $inputs->get('max_price', 999999)
            ]);
        }

        $products = $query->orderBy($inputs->get('sort_by', 'id'), $inputs->get('order_by', 'desc'))
                          ->paginate($inputs->get('per_page', 15));

        return response()->json([
            'data' => $products,
            'filters' => $activeFilters, // Return active filters to frontend
        ]);
    }
}
```

Output Formats
--------------

[](#output-formats)

### As Array

[](#as-array)

```
$inputs = InputBag::make($request)->standard()->toArray();
// Returns: array

// Access values
$search = $inputs['search'];
$perPage = $inputs['per_page'];
```

### As Collection

[](#as-collection)

```
$inputs = InputBag::make($request)->standard()->toCollection();
// Returns: Illuminate\Support\Collection

// Access values using Collection methods
$search = $inputs->get('search');
$perPage = $inputs->get('per_page', 15); // with default
$category = $inputs->get('category');

// Use Collection helper methods
$hasSearch = $inputs->has('search');
$onlyFilters = $inputs->only(['category', 'status', 'featured']);
$exceptPagination = $inputs->except(['page', 'per_page']);

// Chain Collection methods
$filters = $inputs->filter(fn($value) => !is_null($value));
```

### When to Use Each Format

[](#when-to-use-each-format)

**Use Array** when:

- You need simple key-value access
- Working with traditional arrays
- Passing to functions expecting arrays

**Use Collection** when:

- You want Laravel Collection methods
- Need to transform/filter inputs
- Want null-safe access with defaults
- Chaining operations

Configuration
-------------

[](#configuration)

After publishing the configuration file, you can customize:

```
// config/inputbag.php

return [
    // Default values for standard fields
    'defaults' => [
        'per_page' => 15,      // Default items per page
        'sort_by' => 'id',     // Default sort column
        'order_by' => 'desc',  // Default sort direction
    ],

    // Custom fields auto-loaded with standard()
    'custom_fields' => [
        // Simple syntax
        'status' => 'status',

        // Advanced syntax
        'category' => [
            'request_key' => 'category_id',
            'default' => null
        ],
    ],
];
```

API Reference
-------------

[](#api-reference)

### Methods

[](#methods)

#### `make(Request $request)`

[](#makerequest-request)

Creates a new InputBag instance with the given request.

```
InputBag::make($request)
```

**Parameters:**

- `$request` (Request): The HTTP request instance

#### `standard()`

[](#standard)

Processes standard request inputs (search, page, per\_page, sort\_by, order\_by) plus any custom fields defined in config.

```
InputBag::make($request)->standard()
```

#### `set($key, $requestKey, $default = null)`

[](#setkey-requestkey-default--null)

Maps a custom request field to the input bag.

```
InputBag::make($request)->set('status', 'filter_status', 'active')
```

**Parameters:**

- `$key` (string): The key to store the value under in the result
- `$requestKey` (string): The request parameter name to look for
- `$default` (mixed, optional): Default value if request parameter is not present

#### `toArray()`

[](#toarray)

Returns the input bag as an array.

```
InputBag::make($request)->standard()->toArray()
```

#### `toCollection()`

[](#tocollection)

Returns the input bag as a Laravel Collection.

```
InputBag::make($request)->standard()->toCollection()
```

#### `reset()`

[](#reset)

Resets the input bag data.

```
InputBag::make($request)->reset()
```

Usage Patterns
--------------

[](#usage-patterns)

### Pattern 1: Static make() Method (Recommended)

[](#pattern-1-static-make-method-recommended)

```
use Jaikumar0101\LaravelInputbag\InputBag;
use Illuminate\Http\Request;

$inputs = InputBag::make($request)->standard()->toArray();
```

### Pattern 2: Facade (Auto-inject Request)

[](#pattern-2-facade-auto-inject-request)

```
use Jaikumar0101\LaravelInputbag\Facades\InputBag;

$inputs = InputBag::standard()->toArray();
```

### Pattern 3: Direct Instantiation

[](#pattern-3-direct-instantiation)

```
use Jaikumar0101\LaravelInputbag\InputBag;
use Illuminate\Http\Request;

$bag = new InputBag($request);
$inputs = $bag->standard()->toArray();
```

Example API Requests
--------------------

[](#example-api-requests)

### Basic Search and Pagination

[](#basic-search-and-pagination)

```
GET /api/products?search=laptop&page=2&per_page=20

```

### Sorting

[](#sorting)

```
GET /api/products?sort_by=price&order_by=asc

```

### With Custom Filters

[](#with-custom-filters)

```
GET /api/products?search=phone&category=1&status=active&featured=1&price_min=100&price_max=1000

```

### Complete Example

[](#complete-example)

```
GET /api/products?search=laptop&category=electronics&status=active&featured=1&price_min=500&price_max=2000&sort_by=price&order_by=asc&per_page=50&page=2

```

Real-World Use Cases
--------------------

[](#real-world-use-cases)

### Multi-Tenant Application

[](#multi-tenant-application)

```
// config/inputbag.php
'custom_fields' => [
    'tenant_id' => [
        'request_key' => 'tenant',
        'default' => null
    ],
    'workspace_id' => [
        'request_key' => 'workspace',
        'default' => null
    ],
],

// All controllers automatically filter by tenant/workspace
$inputs = InputBag::make($request)->standard()->toArray();
```

### Blog/CMS

[](#blogcms)

```
// config/inputbag.php
'custom_fields' => [
    'status' => [
        'request_key' => 'status',
        'default' => 'published'
    ],
    'author' => 'author_id',
    'tag' => 'tag_id',
    'category' => 'category_id',
],
```

### E-commerce Platform

[](#e-commerce-platform)

```
// config/inputbag.php
'custom_fields' => [
    'category' => 'category_id',
    'brand' => 'brand_id',
    'in_stock' => [
        'request_key' => 'in_stock',
        'default' => null
    ],
    'on_sale' => 'on_sale',
    'min_price' => [
        'request_key' => 'price_min',
        'default' => 0
    ],
    'max_price' => [
        'request_key' => 'price_max',
        'default' => 999999
    ],
],
```

Testing
-------

[](#testing)

Run the test suite:

```
composer test
```

Generate code coverage:

```
composer test-coverage
```

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

Contributing
------------

[](#contributing)

Contributions are welcome! Please feel free to submit a Pull Request.

Security Vulnerabilities
------------------------

[](#security-vulnerabilities)

If you discover a security vulnerability within this package, please send an email to Jai Kumar at . All security vulnerabilities will be promptly addressed.

Credits
-------

[](#credits)

- [Jai Kumar](https://github.com/jaikumar0101)
- [All Contributors](../../contributors)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE) for more information.

---

Made with ❤️ by [Jai Kumar](https://github.com/jaikumar0101)

###  Health Score

38

—

LowBetter than 85% of packages

Maintenance80

Actively maintained with recent releases

Popularity7

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity51

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% 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 ~0 days

Total

6

Last Release

104d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/752c03fcc0f87f8d495425a90f03cdf640082509175be2a5a09d5a27f6533e1b?d=identicon)[Jaikumar0101](/maintainers/Jaikumar0101)

---

Top Contributors

[![Jaikumar0101](https://avatars.githubusercontent.com/u/89125772?v=4)](https://github.com/Jaikumar0101 "Jaikumar0101 (11 commits)")

---

Tags

requestapisearchlaravelpaginationquery builderinputsorting

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/jaikumar0101-laravel-inputbag/health.svg)

```
[![Health](https://phpackages.com/badges/jaikumar0101-laravel-inputbag/health.svg)](https://phpackages.com/packages/jaikumar0101-laravel-inputbag)
```

###  Alternatives

[mollie/laravel-mollie

Mollie API client wrapper for Laravel &amp; Mollie Connect provider for Laravel Socialite

3624.1M28](/packages/mollie-laravel-mollie)[aerni/laravel-spotify

A Laravel wrapper for the Spotify Web API

209145.6k](/packages/aerni-laravel-spotify)[mtownsend/request-xml

The missing XML support for Laravel's Request class.

43432.5k](/packages/mtownsend-request-xml)[acidjazz/metapi

Laravel API helpers

29168.0k](/packages/acidjazz-metapi)

PHPackages © 2026

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