saeedhosan/additions

The package provides classes for Laravel Eloquent, supports

Installs: 30

Dependents: 0

Suggesters: 0

Security: 0

Stars: 0

Watchers: 0

Forks: 0

Open Issues: 0

pkg:composer/saeedhosan/additions

v1.0.0 2026-02-17 18:56 UTC

This package is auto-updated.

Last update: 2026-02-24 22:14:50 UTC


README

GitHub Workflow Status (master) Total Downloads Latest Version License

Laravel additions

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

Table of Contents

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

You can install the package via composer:

composer require saeedhosan/additions

Model Concerns

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

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

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

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

CreateInstance Trait

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

Attach the trait to any class:

use 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

The PreventInstance trait ensures a class cannot be instantiated.

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

use 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

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

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

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 Additions\Eloquent\Concerns\HasBelongsToOne;
use 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

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