PHPackages                             saeedhosan/laravel-additions - 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. [Database &amp; ORM](/categories/database)
4. /
5. saeedhosan/laravel-additions

ActiveLibrary[Database &amp; ORM](/categories/database)

saeedhosan/laravel-additions
============================

The package provides classes for Laravel Eloquent, supports

v0.0.1(3mo ago)01↑2900%MITPHPPHP ^8.2.0CI passing

Since Mar 21Pushed 3w agoCompare

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

READMEChangelog (3)Dependencies (8)Versions (2)Used By (0)

 [![GitHub Workflow Status (master)](https://camo.githubusercontent.com/4d409e479f058f438c570c6590a9962764873983dfae9b09856f057313415620/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f7361656564686f73616e2f6c61726176656c2d75736566756c2f74657374732e796d6c3f6272616e63683d6d61696e266c6162656c3d7465737473267374796c653d726f756e642d737175617265)](https://github.com/saeedhosan/laravel-useful/actions) [![Total Downloads](https://camo.githubusercontent.com/34e8d895ad62eb125992f810dc53e62ab154a0aa28581a7f3b26307859a0d616/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f7361656564686f73616e2f6c61726176656c2d75736566756c)](https://packagist.org/packages/saeedhosan/laravel-useful) [![Latest Version](https://camo.githubusercontent.com/9e9f716a7d2946eaed375f75bea26393df27c044e8ac48e72d8b6c4a41cbe2c6/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f7361656564686f73616e2f6c61726176656c2d75736566756c)](https://packagist.org/packages/saeedhosan/laravel-useful) [![License](https://camo.githubusercontent.com/b777d2edb9d4376cb7e2b730a29fee2f85d3e619ec19233829ac9327b829d0e4/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f7361656564686f73616e2f6c61726176656c2d75736566756c)](https://packagist.org/packages/saeedhosan/laravel-useful)

Laravel useful
==============

[](#laravel-useful)

This package provides Laravel Eloquent support, traits, and additional classes.

Table of Contents
=================

[](#table-of-contents)

- [Introduction](#introduction)
- [Installation](#installation)
- [Model Traits](#model-traits)
    - [HasSlug](#hasslug)
    - [HasUuid](#hasuuid)
    - [HasRouteBinding](#HasRouteBinding)
    - [HasStaticAccess](#hasstaticaccess)
- [Eloquent](#eloquent)
    - [BelongsToOne](#belongsToOne)
- [Commands](#commands)
- [EnvEditor](#EnvEditor)
- [Support](./docs/support.md)

Introduction
------------

[](#introduction)

This package provide collection of reusable php classes to improve everyday Laravel development.

It provides **Eloquent model traits**, **utilities**, and **lightweight traits** that solve common problems - cleanly, safely, and in a Laravel-native way.

Each snippet is intentionally minimal, well-tested, and easy to drop into real-world projects.

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

[](#installation)

You can install the package via composer:

```
composer require saeedhosan/laravel-useful
```

Model Tratis
------------

[](#model-tratis)

The list of model trait that adds some functionalities to laravel Eloquent models

### HasSlug

[](#hasslug)

The `HasSlug` trait adds automatic, unique slug generation to Eloquent models.

It generates slug from the `getSlugSource`, it ensures uniqueness at the database level, and keeps slug in sync when the source value changes.

Apply the trait to any Eloquent model:

```
use SaeedHosan\Useful\Models\Concerns\HasSlug;

class Post extends Model
{
    use HasSlug;
}
```

> **Note** By default, the slug will be generated from the name attribute and stored in the slug column.

Slug Generation &amp; Uniqueness

```
Post::create(['name' => 'Fake Name'])->slug;     // fake-name
Post::create(['name' => 'Fake Name'])->slug;     // fake-name-1
Post::create(['name' => 'Fake Name'])->slug;     // fake-name-2
```

#### Customizable Slug keys and methods

[](#customizable-slug-keys-and-methods)

```
class Post extends Model
{
    use HasSlug;

    /**
     * Get the slug key name.
     */
    public function getSlugKeyName(): string
    {
        return 'slug';
    }

    /**
     * Get the source field for generating slugs.
     */
    public function getSlugSourceName(): string
    {
        return 'title';
    }

    /**
     * Generate a new unique slug for the model.
     */
    public function generateUniqueSlug(): string
    {
        // generate a unique slug
    }

    /**
     * Determine if the slug should be regenerated on update.
     */
    protected function shouldRegenerateSlug(): bool
    {
        return true;
    }
}
```

#### Finding a Model by Slug

[](#finding-a-model-by-slug)

```
$post = Post::findBySlug('fake-name');
```

Returns the first matching model or null if no record exists.

---

A slug is generated if the slug column is empty.

```
Post::create(['name' => 'My Test Name']);
// slug: my-test-name

// Get unique when slug by number for existing record
Post::create(['name' => 'My Test Name']);
// slug: my-test-name-1
```

---

The slug is regenerated when the source attribute changes.

```
$post = Post::create(['name' => 'Original Name']);

$post->update(['name' => 'Updated Name']);
// slug: updated-name
```

### HasUuid

[](#hasuuid)

The `HasUuid` trait adds automatic UUID generation and lookup capabilities to Eloquent models.

It ensures every model receives a unique UUID on creation while allowing control over column naming and behavior.

Apply the trait to any Eloquent model:

```
use SaeedHosan\Useful\Models\Concerns\HasUuid;

class Post extends Model
{
    use HasUuid;

    protected $fillable = ['name'];
}
```

When a model is created, a UUID is automatically generated and stored in the uuid column.

Find Model by UUID

```
$post = Post::findByUuid($uuid);
```

Returns the matching model instance or null if no record is found.

---

Automatic UUID Generation

UUIDs are generated during the creating model event.

```
$post = Post::create(['name' => 'Cyber']);

$post->uuid; // string (26 characters) by default
```

- UUIDs are unique per record
- Existing UUID values are never overridden

---

Accessing the UUID Value

```
$post->getUuidKey();
```

Returns the UUID value for the model, or null if it has not been generated yet.

---

You may override the UUID column name by redefining getUuidKeyName():

```
class Post extends Model
{
    use HasUuid;

    public function getUuidKeyName(): string
    {
        return 'public_id';
    }
}
```

---

If a UUID is manually provided, the trait will respect it:

```
Post::create([
    'name' => 'Custom',
    'uuid' => 'custom-uuid',
]);
```

Database Considerations

For best results add a unique index on the UUID column

```
$table->uuid('uuid')->unique();
```

### HasRouteBinding

[](#hasroutebinding)

This feature makes Eloquent’s `find()` method resolve using the **getRouteKeyName** instead of primary key.

It is useful when your models are identified by a slug, UUID, or any custom route key.

Apply the `HasRouteBinding` trait to your model:

```
use SaeedHosan\Useful\Models\Concerns\HasRouteBinding;

class Post extends Model
{
    use HasRouteBinding;

    public function getRouteKeyName(): string
    {
        return 'slug';
    }
}
```

With the trait applied:

```
Post::find('my-post-slug');
```

Is equivalent to:

```
Post::where('slug', 'my-post-slug')->first();
```

Instead of querying by the primary key.

Example with UUIDs

```
class Order extends Model
{
    use HasRouteBinding;

    public function getRouteKeyName(): string
    {
        return 'uuid';
    }
}

Order::find('01HFYQ3P2YF4K8J9Q6Z8M2X7A1');
```

### HasStaticAccess

[](#hasstaticaccess)

The `HasStaticAccess` trait provides a small set of static helpers for Eloquent models, allowing you to access common model metadata and queries without manually instantiating the model.

Why This Trait Exists?

This trait offers a clean, explicit way to do that while staying aligned with Laravel’s conventions.

Attach the trait to any Eloquent model:

```
use SaeedHosan\Useful\Models\Concerns\HasStaticAccess;

class User extends Model
{
    use HasStaticAccess;
}
```

Available Static Access

```
User::tableName();       // Returns the table name
User::routeKeyName();    // Returns the route key name
User::fields();          // Returns fillable attributes
User::findByKey($key);   // Find model by route key
User::findByRouteKey($key); // Alias of findByKey
```

- Static access without instantiate.
- Improved readability – Clear intent in routing, and helpers.
- Zero side effects – Uses fresh model instances internally.

Eloquent
--------

[](#eloquent)

### BelongsToOne

[](#belongstoone)

The `BelongsToOne` relation provides a one-to-one relationship through a pivot table. It behaves like `belongsToMany`, but returns a single related model insted of first.

Use the `HasBelongsToOne` trait and define the relation with the pivot table and keys:

```
use Illuminate\Database\Eloquent\Model;
use SaeedHosan\Useful\Eloquent\Concerns\HasBelongsToOne;
use SaeedHosan\Useful\Eloquent\Relations\BelongsToOne;

class Blog extends Model
{
    use HasBelongsToOne;

    public function author(): BelongsToOne
    {
        return $this->belongsToOne(Author::class, 'author_blog', 'blog_id', 'author_id');
    }
}
```

Accessing the relation returns a single model (or `null`):

```
$author = $blog->author;
```

Attach and update the relationship through the pivot table:

```
$blog->author()->attach($authorId);
$blog->author()->sync([$authorId]);
```

**Eager Loading**

Eager load it like any other relation:

```
$blogs = Blog::query()->with('author')->get();
```

Commands
--------

[](#commands)

The package provides few commands that are frequntly used for every project

### Make action class

[](#make-action-class)

```
php artisan make:action CreateExampleAction
php artisan make:action CreateExampleAction -i # invokable
```

### Make response class

[](#make-response-class)

```
php artisan make:response CreateExampleResponse
php artisan make:response CreateExampleResponse -i # invokable
```

### EnvEditor

[](#enveditor)

The `EnvEditor` support class provides a simple, safe way to read and modify Laravel `.env` environment variables.

It handles automatic value quoting, escaping of special characters (like double quotes), and ensures your environment configuration stays consistent.

#### Check if a key exists

[](#check-if-a-key-exists)

Use `has(string $key): bool` to determine if a key is present in the `.env` file. Returns `false` if the `.env` file does not exist.

```
use SaeedHosan\Useful\Support\EnvEditor;

EnvEditor::has('APP_NAME'); // true if APP_DEBUG exists, false otherwise
```

#### Add a new key

[](#add-a-new-key)

Use `add(string $key, string $value): bool` to append a new key-value pair to the `.env` file. This will create the `.env` file if it does not exist yet.

```
EnvEditor::add('APP_NAME', 'My Application');
// Appends to .env: APP_NAME="My Application"
```

#### Update an existing key

[](#update-an-existing-key)

Use `update(string $key, string $value): bool` to modify the value of an existing key in the `.env` file. Returns `false` if the key does not exist.

```
EnvEditor::update('APP_DEBUG', 'true');
// Updates existing APP_DEBUG value to "true"
```

#### Add or update (convenience method)

[](#add-or-update-convenience-method)

Use `put(string $key, string $value): bool` to automatically add a new key or update an existing one, without manually checking if the key exists first:

```
EnvEditor::put('DB_HOST', 'localhost');   // Adds new key if DB_HOST does not exist
EnvEditor::put('DB_HOST', '127.0.0.1');  // Updates existing DB_HOST value
```

#### Reload configuration

[](#reload-configuration)

After modifying the `.env` file, use `reloadConfig(): void` to apply changes by clearing cached configuration, re-caching, and restarting queue workers:

```
EnvEditor::reloadConfig();
```

This executes `config:clear`, `config:cache`, `queue:restart`, and clears resolved config instances.

#### Get environment file path

[](#get-environment-file-path)

Use `envPath(): string` to retrieve the full path to the current Laravel `.env` file:

```
EnvEditor::envPath(); // e.g. /path/to/your/project/.env
```

###  Health Score

35

—

LowBetter than 77% of packages

Maintenance89

Actively maintained with recent releases

Popularity2

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity36

Early-stage or recently created project

 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

Unknown

Total

1

Last Release

98d ago

### Community

Maintainers

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

---

Top Contributors

[![saeedhosan](https://avatars.githubusercontent.com/u/78552486?v=4)](https://github.com/saeedhosan "saeedhosan (15 commits)")

###  Code Quality

TestsPest

Static AnalysisPHPStan

Code StyleLaravel Pint

Type Coverage Yes

### Embed Badge

![Health badge](/badges/saeedhosan-laravel-additions/health.svg)

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

###  Alternatives

[anourvalar/eloquent-serialize

Laravel Query Builder (Eloquent) serialization

11222.5M32](/packages/anourvalar-eloquent-serialize)[statamic-rad-pack/runway

Eloquently manage your database models in Statamic.

135212.4k7](/packages/statamic-rad-pack-runway)[mozex/laravel-scout-bulk-actions

Import, flush, and queue-import all your Laravel Scout searchable models at once. Auto-discovers models, runs in bulk, tracks progress.

1437.7k](/packages/mozex-laravel-scout-bulk-actions)[ramadan/easy-model

A Laravel package for enjoyably managing database queries.

111.6k](/packages/ramadan-easy-model)

PHPackages © 2026

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