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. saeedhosan/laravel-additions

ActiveLibrary

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

The package provides classes for Laravel Eloquent, supports

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

Since Mar 21Pushed 1mo 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 1mo ago

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

 [![GitHub Workflow Status (master)](https://camo.githubusercontent.com/ff40a8fea78f6a812b39e7535354bd786a0a8fd7c08f164c84acadb4ac53be6d/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f7361656564686f73616e2f6c61726176656c2d6164646974696f6e732f74657374732e796d6c3f6272616e63683d6d61696e266c6162656c3d7465737473267374796c653d726f756e642d737175617265)](https://github.com/saeedhosan/laravel-additions/actions) [![Total Downloads](https://camo.githubusercontent.com/8af3bf924b1b5f28d56d0c0f5961cec23fbaca5beacd554eca3bc680b2b1a776/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f7361656564686f73616e2f6c61726176656c2d6164646974696f6e73)](https://packagist.org/packages/saeedhosan/laravel-additions) [![Latest Version](https://camo.githubusercontent.com/f83c0ac9cc4927e5e4568bc4cb374505134bc69a7c6554c5610426a46d4f6abe/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f7361656564686f73616e2f6c61726176656c2d6164646974696f6e73)](https://packagist.org/packages/saeedhosan/laravel-additions) [![License](https://camo.githubusercontent.com/93412a38b947293f2f1210e8f0281c4719c7dd35d98fbec17993e4e7c9e56e55/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f7361656564686f73616e2f6c61726176656c2d6164646974696f6e73)](https://packagist.org/packages/saeedhosan/laravel-additions)

Laravel additions
=================

[](#laravel-additions)

The additions package provides Laravel Eloquent, supports, traits, and additional classes.

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

[](#table-of-contents)

- [Introduction](#introduction)
- [Installation](#installation)
- [Model Concerns](#model-concerns)
    - [HasSlug Trait](#hasslug-trait)
    - [HasUuid Trait](#hasuuid-trait)
    - [HasRouteBinding](#HasRouteBinding)
    - [HasStaticAccess](#hasstaticaccess)
- [Support](#support)
    - [Traits](#support-traits)
    - [Path](#support-path)
    - [Json](#support-json)
    - [EnvEditor](#envEditor)
- [Eloquent Relations](#eloquent-relations)
    - [BelongsToOne](#belongsToOne)

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

[](#introduction)

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

It provides **Eloquent model traits**, **support 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-additions
```

Model Concerns
--------------

[](#model-concerns)

### HasSlug Concern

[](#hasslug-concern)

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\Additions\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

```
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

```
$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 Concern

[](#hasuuid-concern)

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\Additions\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\Additions\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\Additions\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.

Support
-------

[](#support)

### CreateInstance Trait

[](#createinstance-trait)

The `CreateInstance` trait provides convenient, expressive ways to create class instances using static cache.

Attach the trait to any class:

```
use SaeedHosan\Additions\Support\Traits\CreateInstance;

class ReportGenerator
{
    use CreateInstance;

    public function __construct(private string $name) {}

    public function getName(){
        return $this->name;
    }
}
```

Creating Instances via the Container

Use `make()` to resolve the class through Laravel’s service container.

```
$report = ReportGenerator::make('Laravel is')->getName(); // Laravel is
```

### PreventInstance Trait

[](#preventinstance-trait)

The `PreventInstance` trait ensures a class cannot be instantiated.

Apply the trait to a class meant for static usage only:

```
use SaeedHosan\Additions\Support\Traits\PreventInstance;

class StringHelpers
{
    use PreventInstance;

    public static function upper(string $value): string
    {
        return strtoupper($value);
    }
}
```

Attempting to instantiate the class will throw a LogicException:

```
new StringHelpers();
// LogicException: StringHelpers cannot be instantiated.
```

### Support Path

[](#support-path)

The `Path` class provides simple, cross-platform utilities for working with file system paths. It focuses on **normalization**, **joining**, and **safe path inspection**, without side effects.

Join multiple path segments into a clean, normalized path:

```
use SaeedHosan\Additions\Support\Path;

Path::join('storage', 'app', 'files');
// storage/app/files
```

Handles duplicate slashes and mixed separators automatically.

---

Normalize a path by: Converting `\` to `/` Removing `./` and removing duplicate slashes

```
Path::normalize('storage\\app//./files');
// storage/app/files
```

---

Get the directory of the file where Path::current() is called:

```
Path::current('config', 'files');
// /current/file/dir/config/files
```

Useful for resolving paths relative to the calling file.

---

Resolving Real Paths - Resolve a path to its absolute form (if it exists):

```
Path::real('./storage/app');
// /full/path/to/storage/app
```

Returns null if the path does not exist.

---

Replacing Path Segments - Replace the first occurrence:

```
Path::replaceFirst('storage', 'public', 'storage/app/file.txt');
// public/app/file.txt
```

Replace all occurrences:

```
Path::replace('/', '-', 'storage/app/file.txt');
// storage-app-file.txt
```

---

Path Information - Get common path parts:

```
Path::dirname('/var/www/index.php');
// /var/www

Path::basename('/var/www/index.php');
// index.php

Path::filename('/var/www/index.php');
// index

Path::extension('/var/www/index.php');
// php
```

---

Absolute Path Detection - Check if a path is absolute (Linux or Windows):

```
Path::isAbsolute('/var/www');     // true
Path::isAbsolute('C:\\Windows'); // true
Path::isAbsolute('storage/app'); // false
```

### Support Json

[](#support-json)

The `Json` class provides a simple, safe way to **check** and **decode** JSON values without throwing errors.

It is designed for defensive code where input may be invalid, empty, or unknown.

**Checking if a Value Is JSON**

Use `Json::is()` to determine whether a value is a **valid JSON string**.

```
use SaeedHosan\Additions\Support\Json;

Json::is('{"name":"Saeed"}'); // true
Json::is('[1,2,3]');          // true
Json::is('"string"');         // true
Json::is('null');             // true

Json::is('{invalid-json}');   // false
Json::is('');                 // false
Json::is(123);                // false
Json::is(null);               // false
```

Only valid JSON strings return true.

---

**Decoding JSON Safely**

Use Json::decode() to decode JSON into an array without exceptions.

```
Json::decode('{"name":"Saeed"}');
// ['name' => 'Saeed']

Json::decode('[1,2,3]');
// [1, 2, 3]
```

**Default Fallback Value**

You may provide a default value when decoding fails:

```
$default = ['default' => true];

Json::decode(null, $default);            // ['default' => true]
Json::decode('{invalid-json}', $default); // ['default' => true]
Json::decode('"string"', $default);       // ['default' => true]
Json::decode('123', $default);             // ['default' => true]
```

**Summary**

- `Json::is()` checks if a value is valid JSON
- `Json::decode()` safely decodes JSON into an array
- No exceptions, no warnings
- Ideal for handling user input, config values, or external data

Eloquent relations
------------------

[](#eloquent-relations)

### 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\Additions\Eloquent\Concerns\HasBelongsToOne;
use SaeedHosan\Additions\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();
```

### EnvEditor

[](#enveditor)

The `EnvEditor` support class provides a simple way to modify laravel environment variables.

It handles quoting, escaping, and ensures your environment configuration stays consistent.

```
use SaeedHosan\Additions\Support\EnvEditor;

EnvEditor::addKey('APP_NAME', 'My Application');
// APP_NAME="My Application"

EnvEditor::editKey('APP_DEBUG', 'true');

EnvEditor::setKey('APP_URL', 'https://example.com');

EnvEditor::keyExists('APP_DEBUG'); // bool
```

The `put()` method works like `setKey()` and before check with `keyExists`:

```
EnvEditor::put('DB_HOST', 'localhost'); // add new
EnvEditor::put('DB_HOST', '127.0.0.1'); // Updates existing
```

###  Health Score

35

—

LowBetter than 79% of packages

Maintenance90

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

52d 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 (1 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

11320.2M21](/packages/anourvalar-eloquent-serialize)[namu/wirechat

A Laravel Livewire messaging app for teams with private chats and group conversations.

54324.5k](/packages/namu-wirechat)[statamic-rad-pack/runway

Eloquently manage your database models in Statamic.

135192.6k5](/packages/statamic-rad-pack-runway)

PHPackages © 2026

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