PHPackages                             hindbiswas/laravel-model-utils - 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. [Utility &amp; Helpers](/categories/utility)
4. /
5. hindbiswas/laravel-model-utils

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

hindbiswas/laravel-model-utils
==============================

A lightweight Laravel package for Model traits and utilities

v1.1.1(1mo ago)040MITPHPPHP ^8.3CI passing

Since Apr 14Pushed 1mo agoCompare

[ Source](https://github.com/hind-sagar-biswas/laravel-model-utils)[ Packagist](https://packagist.org/packages/hindbiswas/laravel-model-utils)[ Docs](https://github.com/hind-sagar-biswas/laravel-model-utils)[ GitHub Sponsors]()[ RSS](/packages/hindbiswas-laravel-model-utils/feed)WikiDiscussions main Synced 1w ago

READMEChangelog (3)Dependencies (12)Versions (4)Used By (0)

Laravel Model Utils
===================

[](#laravel-model-utils)

[![Latest Version on Packagist](https://camo.githubusercontent.com/5f2db80b6939aea33c1c247b5bebe6073ed9180a511ab8fff240c6ba6039e333/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f68696e646269737761732f6c61726176656c2d6d6f64656c2d7574696c732e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/hindbiswas/laravel-model-utils)[![GitHub Tests Action Status](https://camo.githubusercontent.com/f714696feabe73a8b08946e40ed52fe246b2808058d48711766b0a00dbe78f82/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f68696e646269737761732f6c61726176656c2d6d6f64656c2d7574696c732f72756e2d74657374732e796d6c3f6272616e63683d6d61696e266c6162656c3d7465737473267374796c653d666c61742d737175617265)](https://github.com/hind-sagar-biswas/laravel-model-utils/actions?query=workflow%3Arun-tests+branch%3Amain)[![GitHub Code Style Action Status](https://camo.githubusercontent.com/4ad70bcbff1a95fbf0341a50f8932925f3f2f384de1e85790173afff1fede122/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f68696e646269737761732f6c61726176656c2d6d6f64656c2d7574696c732f6669782d7068702d636f64652d7374796c652d6973737565732e796d6c3f6272616e63683d6d61696e266c6162656c3d636f64652532307374796c65267374796c653d666c61742d737175617265)](https://github.com/hind-sagar-biswas/laravel-model-utils/actions?query=workflow%3A%22Fix+PHP+code+style+issues%22+branch%3Amain)[![Total Downloads](https://camo.githubusercontent.com/0c40b7c21e96803fd76d112845b334429ed32597c75a90440789128322f800a1/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f68696e646269737761732f6c61726176656c2d6d6f64656c2d7574696c732e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/hindbiswas/laravel-model-utils)

A lightweight Laravel package that adds practical Eloquent model traits and utilities.

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

[](#installation)

```
composer require hindbiswas/laravel-model-utils
```

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

[](#requirements)

- PHP 8.3+
- Laravel 11, 12, or 13

Included Features
-----------------

[](#included-features)

- `BelongsToAuth`: auto-assign `user_id` when an authenticated user creates a model.
- `Optionable`: convert model records to `value`/`label` option arrays.
- `Filterable`: dynamic exact filters plus relationship-aware search with dot notation.
- `HasSlug`: generate slugs from model attributes with optional uniqueness and update behavior.
- `Archivable`: archive/restore records with query scopes for active and archived models.
- `EnumUtil`: convert PHP enums to arrays, CSV, associative maps, and options.

Usage
-----

[](#usage)

### BelongsToAuth Trait

[](#belongstoauth-trait)

```
use HindBiswas\ModelUtils\Traits\BelongsToAuth;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    use BelongsToAuth;

    protected $guarded = [];
}
```

Behavior:

- If `user_id` is empty and a user is authenticated, `user_id` is filled from `Auth::id()`.
- If `user_id` is already present, it is not overridden.

### Optionable Trait

[](#optionable-trait)

```
use HindBiswas\ModelUtils\Traits\Optionable;
use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    use Optionable;

    protected $guarded = [];
}
```

```
Category::options();
// [
//   ['value' => 1, 'label' => 'Books'],
//   ['value' => 2, 'label' => 'Games'],
// ]
```

You can override the columns used for options:

```
protected static function optionValue(): string
{
    return 'code';
}

protected static function optionLabel(): string
{
    return 'title';
}
```

### Filterable Trait

[](#filterable-trait)

```
use HindBiswas\ModelUtils\Traits\Filterable;
use Illuminate\Database\Eloquent\Model;

class Article extends Model
{
    use Filterable;

    protected $guarded = [];

    protected array $filterable = [
        'status',
        'author.name',
        'author.organization.name',
    ];

    protected array $searchable = [
        'title',
        'author.name',
        'author.organization.name',
    ];
}
```

```
$articles = Article::query()->filter([
    'status' => 'published',
    'author.name' => 'Alice',
    'search' => 'Laravel',
])->get();
```

Notes:

- Exact filters use `where` and `whereHas`.
- Search uses grouped `orWhere` and `orWhereHas` with `%search%` matching.
- Dot notation supports nested relations like `owner.user.name`.

### HasSlug Trait

[](#hasslug-trait)

```
use HindBiswas\ModelUtils\Traits\HasSlug;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    use HasSlug;

    protected $guarded = [];

    protected function slugSource(): array
    {
        return ['title'];
    }

    protected function slugUniqueScope(): array|bool
    {
        return true;
    }

    protected function updateSlugOnUpdate(): bool
    {
        return true;
    }
}
```

Available hooks:

- `slugField()`: slug column name (default: `slug`).
- `slugSource()`: source attributes used to build slug.
- `slugUniqueScope()`: controls uniqueness.
    - `false`: no uniqueness checks.
    - `true`: unique across table.
    - `['tenant_id']`: unique within a scope.
- `maxSlugLength()`: maximum slug length (default: `255`).
- `updateSlugOnUpdate()`: regenerate slug when source fields change.

`getRouteKeyName()` returns `slugField()`.

### Archivable Trait

[](#archivable-trait)

```
use HindBiswas\ModelUtils\Traits\Archivable;
use Illuminate\Database\Eloquent\Model;

class Document extends Model
{
    use Archivable;

    protected $guarded = [];
}
```

Your table should have an `archived_at` nullable datetime column.

```
Schema::table('documents', function (Blueprint $table) {
    $table->dateTime('archived_at')->nullable();
});
```

```
$document->archive();
$document->restoreArchive();
$document->isArchived();

Document::query()->onlyArchived()->get();
Document::query()->withArchived()->get();
```

Behavior:

- Active records are returned by default because a global scope excludes archived rows.
- `onlyArchived()` fetches only archived records.
- `withArchived()` fetches both active and archived records.
- `archived_at` is cast to `datetime` automatically.

### EnumUtil Helper

[](#enumutil-helper)

```
use HindBiswas\ModelUtils\Utils\EnumUtil;

enum OrderStatus: string
{
    case Draft = 'draft';
    case Published = 'published';
}

EnumUtil::toArray(OrderStatus::class);
// ['draft', 'published']

EnumUtil::toCSV(OrderStatus::class);
// 'draft,published'

EnumUtil::toAssocArray(OrderStatus::class);
// ['draft' => 'Draft', 'published' => 'Published']

EnumUtil::toOptions(OrderStatus::class);
// [
//   ['value' => 'draft', 'label' => 'Draft'],
//   ['value' => 'published', 'label' => 'Published'],
// ]
```

If enum cases implement a `label()` method, `EnumUtil` uses it. Otherwise, labels are generated using `Str::headline(...)`.

Changelog
---------

[](#changelog)

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

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

[](#contributing)

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

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

[](#security-vulnerabilities)

Please review [our security policy](../../security/policy) on how to report security vulnerabilities.

Credits
-------

[](#credits)

- [Hind Biswas Krishna](https://github.com/hind-sagar-biswas)
- [All Contributors](../../contributors)

License
-------

[](#license)

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

###  Health Score

42

—

FairBetter than 88% of packages

Maintenance90

Actively maintained with recent releases

Popularity10

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity51

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 87% 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 ~3 days

Total

3

Last Release

50d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/1f80c3a03d68d7009942d400a5e29d6f56c203405870e58c9073d5a8dd03b5f7?d=identicon)[HindSagarBiswas](/maintainers/HindSagarBiswas)

---

Top Contributors

[![hind-sagar-biswas](https://avatars.githubusercontent.com/u/69765092?v=4)](https://github.com/hind-sagar-biswas "hind-sagar-biswas (20 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (2 commits)")[![github-actions[bot]](https://avatars.githubusercontent.com/in/15368?v=4)](https://github.com/github-actions[bot] "github-actions[bot] (1 commits)")

---

Tags

laravel-packageutilitylaravelHind Biswaslaravel-model-utils

###  Code Quality

TestsPest

Static AnalysisPHPStan

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/hindbiswas-laravel-model-utils/health.svg)

```
[![Health](https://phpackages.com/badges/hindbiswas-laravel-model-utils/health.svg)](https://phpackages.com/packages/hindbiswas-laravel-model-utils)
```

###  Alternatives

[spatie/laravel-data

Create unified resources and data transfer objects

1.8k33.0M871](/packages/spatie-laravel-data)[spatie/laravel-pdf

Create PDFs in Laravel apps

1.0k4.3M41](/packages/spatie-laravel-pdf)[codewithdennis/filament-select-tree

The multi-level select field enables you to make single selections from a predefined list of options that are organized into multiple levels or depths.

327482.0k25](/packages/codewithdennis-filament-select-tree)[nativephp/desktop

NativePHP for Desktop

37833.6k8](/packages/nativephp-desktop)[worksome/exchange

Check Exchange Rates for any currency in Laravel.

124581.3k](/packages/worksome-exchange)[rawilk/profile-filament-plugin

Profile &amp; MFA starter kit for filament.

3913.7k](/packages/rawilk-profile-filament-plugin)

PHPackages © 2026

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