PHPackages                             sebastiansulinski/laravel-bits - 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. sebastiansulinski/laravel-bits

ActiveProject

sebastiansulinski/laravel-bits
==============================

A set of handy utilities for any Laravel project.

v1.3.1(3mo ago)0112↓100%MITPHPPHP ^8.4

Since Jul 30Pushed 1mo agoCompare

[ Source](https://github.com/sebastiansulinski/laravel-bits)[ Packagist](https://packagist.org/packages/sebastiansulinski/laravel-bits)[ RSS](/packages/sebastiansulinski-laravel-bits/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (5)Dependencies (6)Versions (10)Used By (0)

Laravel Bits
============

[](#laravel-bits)

A set of handy utilities for any Laravel project.

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

[](#requirements)

- PHP ^8.4
- Laravel ^12.0

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

[](#installation)

You can install the package via Composer:

```
composer require sebastiansulinski/laravel-bits
```

The package will automatically register its service provider.

Available Traits
----------------

[](#available-traits)

### EnhancedEnums

[](#enhancedenums)

The `EnhancedEnums` trait provides additional utility methods for PHP enums, making them more convenient to work with in Laravel applications.

#### Usage

[](#usage)

```
use LaravelBits\Traits\EnhancedEnums;

enum Status: string
{
    use EnhancedEnums;

    case Active = 'active';
    case Pending = 'pending';
    case Closed = 'closed';

    public function label(): string
    {
        return ucfirst($this->value) . ' Status';
    }
}
```

#### Available Methods

[](#available-methods)

- **`values(?array $cases = null): array`** - Get array of enum values
- **`names(?array $cases = null): array`** - Get array of enum names
- **`options(?array $cases = null): array`** - Get array of name/value pairs
- **`toArray(): array`** - Convert enum instance to array
- **`label(): string`** - Get label for enum case (can be overridden)
- **`except(array|self $cases): array`** - Exclude certain cases from enum
- **`collection(): Collection`** - Get cases as Laravel Collection

#### Examples

[](#examples)

```
// Get all values
Status::values(); // ['active', 'pending', 'closed']

// Get all names
Status::names(); // ['Active', 'Pending', 'Closed']

// Get options for dropdowns
Status::options();
// [
//     ['name' => 'Active Status', 'value' => 'active'],
//     ['name' => 'Pending Status', 'value' => 'pending'],
//     ['name' => 'Closed Status', 'value' => 'closed']
// ]

// Convert single case to array
Status::Active->toArray(); // ['name' => 'Active Status', 'value' => 'active']

// Exclude certain cases
Status::except([Status::Active, Status::Closed]); // Only Pending case

// Get as Collection
Status::collection(); // Collection of all cases
```

### Serialisable

[](#serialisable)

The `Serialisable` trait provides JSON serialization capabilities for any class.

#### Usage

[](#usage-1)

```
use LaravelBits\Traits\Serialisable;

class MyClass
{
    use Serialisable;

    public function toArray(): array
    {
        return [
            'property1' => $this->property1,
            'property2' => $this->property2,
        ];
    }
}
```

#### Available Methods

[](#available-methods-1)

- **`__toString(): string`** - Convert object to JSON string
- **`toJson($options = 0): string`** - Get JSON representation of the object
- **`toArray(): array`** - Abstract method that must be implemented

#### Examples

[](#examples-1)

```
$object = new MyClass();

// Convert to JSON string
echo $object; // Calls __toString() which returns JSON

// Get JSON with options
$json = $object->toJson(JSON_PRETTY_PRINT);
```

### Sortable

[](#sortable)

The `Sortable` trait provides utilities for handling sortable records with automatic sort position management.

#### Usage

[](#usage-2)

```
use LaravelBits\Traits\Sortable;

class MySortableService
{
    use Sortable;

    public function sort(array $ids): void
    {
        MyModel::upsert(
            $this->sortablePayload($ids), 'ulid', ['sort']
        );
    }

    protected function existingSortables(array $ids): Collection
    {
        return MyModel::whereIn('ulid', $ids)->get();
    }

    protected function sortableModelColumns(): array
    {
        return ['ulid', 'name', 'description'];
    }
}
```

### Sorter

[](#sorter)

The `Sorter` and `SorterPayload` classes provide a powerful way to reorder records based on a new sequence of IDs while maintaining proper sort values. This is particularly useful for drag-and-drop interfaces or any scenario where you need to update the sort order of multiple records efficiently.

#### SorterPayload

[](#sorterpayload)

The `SorterPayload` class prepares a collection of models in the desired order based on an array of IDs.

**Constructor Parameters:**

- **`$models`** - Collection of Eloquent models to be reordered
- **`$ids`** - Array of IDs in the desired order
- **`$filter`** - String column name or Closure to match models with IDs (defaults to 'id')

#### Sorter

[](#sorter-1)

The `Sorter` class generates update sets for bulk database operations based on the reordered payload.

**Constructor Parameters:**

- **`$payload`** - SorterPayload instance with reordered records
- **`$idColumn`** - Column name used as the primary key (defaults to 'id'). When used in combination with Eloquent `Builder::updateMany()`, this should match the first argument `$caseColumn`.
- **`$sortColumn`** - Column name used for sorting (defaults to 'sort')
- **`$updateColumn`** - Column name to update (defaults to 'sort')

**Methods:**

- **`getSet(?Closure $callback = null): UpdateManySet`** - Generate an UpdateManySet for bulk updates

#### Usage Examples

[](#usage-examples)

**Basic Sorting:**

```
use LaravelBits\Utilities\Sorter\Sorter;
use LaravelBits\Utilities\Sorter\SorterPayload;

// Get your models
$models = Book::where('category_id', 1)->get();

// Define the new order using IDs
$newOrder = [3, 1, 4, 2, 5]; // Book IDs in desired order

// Create the payload
$payload = new SorterPayload(
    models: $models,
    ids: $newOrder,
    filter: 'id' // Match by 'id' column
);

// Create the sorter
$sorter = new Sorter(payload: $payload);

// Get the update set and apply it
$updateSet = $sorter->getSet();
Book::updateMany('id', $updateSet);
```

**Advanced Sorting with Custom Columns:**

```
// Using ULID as identifier and custom sort column
$models = Product::where('active', true)->get();
$ulidOrder = ['01H123...', '01H456...', '01H789...']; // ULIDs in desired order

$payload = new SorterPayload(
    models: $models,
    ids: $ulidOrder,
    filter: fn($model, $ulid) => $model->ulid->toString() === $ulid
);

$sorter = new Sorter(
    payload: $payload,
    idColumn: 'id',
    sortColumn: 'position',
    updateColumn: 'position'
);

$updateSet = $sorter->getSet();
Product::updateMany('id', $updateSet);
```

**Custom Value Generation:**

```
// Generate custom values with a callback
$sorter = new Sorter(
    payload: $payload,
    updateColumn: 'display_name'
);

$updateSet = $sorter->getSet(
    fn($model, $index, $sort) => "Item #{$index} (Sort: {$sort})"
);

Product::updateMany('id', $updateSet);
```

The callback function receives three parameters:

- **`$model`** - The current Eloquent model
- **`$index`** - Zero-based index in the reordered sequence
- **`$sort`** - The calculated sort value for this position

Available Macros
----------------

[](#available-macros)

### QueryBuilder whereDateBetween

[](#querybuilder-wheredatebetween)

Adds a `whereDateBetween` method to Laravel's Query Builder for filtering records between two dates.

#### Usage

[](#usage-3)

```
use Illuminate\Support\Facades\DB;

// Filter records between two dates
DB::table('orders')
    ->whereDateBetween('created_at', ['2024-01-01', '2024-12-31'])
    ->get();

// With custom boolean operator
DB::table('orders')
    ->where('status', 'active')
    ->whereDateBetween('created_at', ['2024-01-01', '2024-12-31'], 'or')
    ->get();
```

#### Parameters

[](#parameters)

- **`$column`** - The column name to filter
- **`$dates`** - Array with two dates `[start_date, end_date]`
- **`$boolean`** - Boolean operator ('and' or 'or'), defaults to 'and'

### QueryBuilder whereLowercase

[](#querybuilder-wherelowercase)

Adds a `whereLowercase` method to Laravel's Query Builder for comparing a column against a lowercased value. Works with both Query Builder and Eloquent Builder. Accepts the same arguments as the `where` method.

#### Usage

[](#usage-4)

```
use Illuminate\Support\Facades\DB;

// Simple equality check - lowercases the value automatically
DB::table('users')
    ->whereLowercase('email', 'John@Example.COM')
    ->get();
// Equivalent to: ->where('email', 'john@example.com')

// With Eloquent
User::query()
    ->whereLowercase('email', $request->email)
    ->first();

// With a custom operator
User::query()
    ->whereLowercase('email', '!=', 'ADMIN@EXAMPLE.COM')
    ->get();

// With boolean operator
User::query()
    ->where('name', 'John')
    ->whereLowercase('email', '=', 'JANE@EXAMPLE.COM', 'or')
    ->get();
```

#### Parameters

[](#parameters-1)

- **`$column`** - The column name to filter
- **`$operator`** - Comparison operator (defaults to '=') or the value when using 2-argument form
- **`$value`** - The value to lowercase and compare against
- **`$boolean`** - Boolean operator ('and' or 'or'), defaults to 'and'

### EloquentBuilder updateMany

[](#eloquentbuilder-updatemany)

Adds an `updateMany` method to Laravel's Eloquent Builder for efficiently updating multiple records with different values in a single query.

#### Usage

[](#usage-5)

```
use App\Models\Book;
use LaravelBits\Data\UpdateManySet;

// Update multiple records with different sort values
Book::updateMany('id', new UpdateManySet('sort', [
    1 => 30,
    2 => 20,
    3 => 10,
]));

// Update multiple columns at once
Book::updateMany('id', [
    new UpdateManySet('sort', [1 => 30, 2 => 20, 3 => 10]),
    new UpdateManySet('priority', [1 => 'high', 2 => 'medium', 3 => 'low']),
]);

// With custom timestamp
Book::updateMany('id', new UpdateManySet('sort', [
    1 => 30,
    2 => 20,
    3 => 10,
]), now()->addHour());
```

#### Parameters

[](#parameters-2)

- **`$caseColumn`** - The column to match against (usually 'id')
- **`$sets`** - UpdateManySet instance or array of UpdateManySet instances
- **`$timestamp`** - Optional timestamp for updated\_at (defaults to now())

#### Benefits

[](#benefits)

- **Performance**: Updates multiple records in a single SQL query using CASE statements
- **Efficiency**: Avoids N+1 query problems when updating many records
- **Automatic timestamps**: Automatically updates the `updated_at` column

Available Casts
---------------

[](#available-casts)

### Lowercase

[](#lowercase)

The `Lowercase` cast automatically converts string values to lowercase when getting and setting model attributes. This is useful for normalizing data like email addresses.

#### Usage

[](#usage-6)

```
use Illuminate\Database\Eloquent\Model;
use LaravelBits\Casts\Lowercase;

class User extends Model
{
    protected function casts(): array
    {
        return [
            'email' => Lowercase::class,
        ];
    }
}
```

#### Examples

[](#examples-2)

```
$user = new User(['email' => 'JOHN@EXAMPLE.COM']);
$user->email; // 'john@example.com'

$user->email = 'Jane@Example.COM';
$user->email; // 'jane@example.com'

// Null values are preserved
$user->email = null;
$user->email; // null
```

License
-------

[](#license)

This package is open-sourced software licensed under the [MIT license](https://opensource.org/licenses/MIT).

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

[](#contributing)

Please see [CONTRIBUTING](CONTRIBUTING.md) for details.

Credits
-------

[](#credits)

- [Sebastian Sulinski](https://github.com/sebastiansulinski)

###  Health Score

43

—

FairBetter than 91% of packages

Maintenance87

Actively maintained with recent releases

Popularity10

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity59

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 ~27 days

Recently: every ~42 days

Total

8

Last Release

96d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/2211203?v=4)[Sebastian Sulinski](/maintainers/sebastiansulinski)[@sebastiansulinski](https://github.com/sebastiansulinski)

---

Top Contributors

[![sebastiansulinski](https://avatars.githubusercontent.com/u/2211203?v=4)](https://github.com/sebastiansulinski "sebastiansulinski (19 commits)")

###  Code Quality

TestsPest

Static AnalysisPHPStan

Code StyleLaravel Pint

Type Coverage Yes

### Embed Badge

![Health badge](/badges/sebastiansulinski-laravel-bits/health.svg)

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

###  Alternatives

[binaryk/laravel-restify

Laravel REST API helpers

651399.1k](/packages/binaryk-laravel-restify)[anourvalar/eloquent-serialize

Laravel Query Builder (Eloquent) serialization

11320.2M21](/packages/anourvalar-eloquent-serialize)[dragon-code/laravel-deploy-operations

Performing any actions during the deployment process

240173.5k2](/packages/dragon-code-laravel-deploy-operations)

PHPackages © 2026

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