saeedhosan/laravel-useful

The package provides classes for Laravel Eloquent, supports

Maintainers

Package info

github.com/saeedhosan/laravel-useful

pkg:composer/saeedhosan/laravel-useful

Statistics

Installs: 357

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 0

v0.0.1 2026-05-02 10:04 UTC

This package is auto-updated.

Last update: 2026-05-02 10:06:49 UTC


README

GitHub Workflow Status (master) Total Downloads Latest Version License

Laravel useful

This package provides Laravel Eloquent support, 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, 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/laravel-useful

Model Tratis

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

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

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

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

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

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

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

Make action class

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

Make response class

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

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

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

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

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)

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

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

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

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