PHPackages                             twenycode/laravel-blueprint - 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. twenycode/laravel-blueprint

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

twenycode/laravel-blueprint
===========================

Core components and utilities for Laravel applications

v2.2.1(5mo ago)077MITPHPPHP ^8.2

Since Mar 28Pushed 5mo agoCompare

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

READMEChangelog (10)Dependencies (10)Versions (51)Used By (0)

Laravel Blueprint
=================

[](#laravel-blueprint)

A comprehensive architecture and utilities package for Laravel applications that provides a standardized structure, core components, and common patterns to accelerate development.

[![Latest Version on Packagist](https://camo.githubusercontent.com/d2330d1f7a9f83017be851a83d69419222ff9db2a0c88c4086ccbbd2ef6720f9/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f7477656e79636f64652f6c61726176656c2d626c75657072696e742e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/twenycode/laravel-blueprint)[![Total Downloads](https://camo.githubusercontent.com/0d822b4e7c8bea3847d5a5354d849253c80727c052aa9400ea3ed6824e7fe20d/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f7477656e79636f64652f6c61726176656c2d626c75657072696e742e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/twenycode/laravel-blueprint)[![MIT Licensed](https://camo.githubusercontent.com/55c0218c8f8009f06ad4ddae837ddd05301481fcf0dff8e0ed9dadda8780713e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d627269676874677265656e2e7376673f7374796c653d666c61742d737175617265)](LICENSE.md)

Table of Contents
-----------------

[](#table-of-contents)

- [Introduction](#introduction)
- [Features](#features)
- [Requirements](#requirements)
- [Installation](#installation)
- [Configuration](#configuration)
- [Architecture Overview](#architecture-overview)
- [ID Management Approaches](#id-management-approaches)
- [Quick Start Guide](#quick-start-guide)
- [Core Components](#core-components)
- [Helper Functions](#helper-functions)
- [Caching System](#caching-system)
- [SweetAlert Integration](#sweetalert-integration)
- [Blade Morph Integration](#blade-morph-integration)
- [Testing](#testing)
- [Migration Guide](#migration-guide)
- [Best Practices](#best-practices)
- [API Documentation](#api-documentation)
- [Troubleshooting](#troubleshooting)
- [Contributing](#contributing)
- [License](#license)
- [Support](#support)

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

[](#introduction)

Laravel Blueprint provides a solid foundation for building Laravel applications with a clean architecture, standardized patterns, and reusable components. It implements the repository pattern, service layer, and includes numerous utilities and base classes to streamline your development process.

### Why Laravel Blueprint?

[](#why-laravel-blueprint)

- **Standardized Architecture**: Follow proven patterns out of the box
- **Time-Saving**: Pre-built components for common tasks
- **Flexible**: Choose between hashed IDs or UUIDs
- **Performance**: Built-in intelligent caching system
- **Maintainable**: Clear separation of concerns
- **Well-Tested**: Comprehensive error handling and logging

Features
--------

[](#features)

### 🏗️ **Architecture Components**

[](#️-architecture-components)

- **Repository Pattern** - Comprehensive data access layer with built-in caching support
- **Service Layer** - Business logic abstraction with database transaction management
- **Resource Controllers** - Base controllers with CRUD operations, error handling, and flash messaging
- **Form Request Validation** - Permission-based request validation with custom rules

### 🔧 **Model &amp; Database**

[](#-model--database)

- **Enhanced Models** - Feature-rich base models with common attributes and methods
- **Dual ID Support** - Choose between hashed integer IDs or native Laravel UUIDs
- **Soft Delete Support** - Ready-to-use methods for handling soft deletes
- **Activity Logging** - Integrated Spatie Activity Log for audit trails
- **Migration Helpers** - Standardized migration patterns for both ID types

### 🚀 **Performance &amp; Caching**

[](#-performance--caching)

- **Intelligent Caching** - Automatic cache management with model observers
- **User-Specific Caching** - Context-aware caching for multi-tenant applications
- **Cache Invalidation** - Automatic cache clearing on model changes
- **Tag-Based Cache** - Efficient cache management with Redis/Memcached

### 🎨 **UI &amp; UX**

[](#-ui--ux)

- **Flash Messaging** - Integrated SweetAlert for beautiful notifications
- **Error Handling** - Standardized error handling across all components
- **API Support** - JSON response handling for API controllers
- **Bootstrap Pagination** - Pre-configured pagination styling
- **Blade Morph** - Smooth UI transitions and morphing effects

### 🛠️ **Utilities &amp; Helpers**

[](#️-utilities--helpers)

- **Helper Functions** - Extensive utility functions for dates, text, and numbers
- **Custom Validation Rules** - Composite key uniqueness validation
- **Text Processing** - Advanced text manipulation and formatting functions
- **File Size Formatting** - Human-readable file size conversion

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

[](#requirements)

- **PHP:** 8.2 or higher
- **Laravel:** 10.0, 11.0, or 12.0
- **Cache Driver:** Redis or Memcached (for tag-based cache invalidation)
- **Dependencies:**
    - vinkla/hashids: ^13.0
    - realrashid/sweet-alert: ^7.3
    - twenycode/blade-morph: ^1.3
    - spatie/laravel-activitylog: ^4.10
    - spatie/laravel-permission: ^6.21
    - rap2hpoutre/laravel-log-viewer: ^2.4
    - rappasoft/laravel-authentication-log: ^4.0

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

[](#installation)

### Step 1: Install the Package

[](#step-1-install-the-package)

Install the package via Composer:

```
composer require twenycode/laravel-blueprint
```

### Step 2: Publish Configuration

[](#step-2-publish-configuration)

Publish the configuration files:

```
php artisan vendor:publish --provider="TwenyCode\LaravelBlueprint\TwenyLaravelBlueprintServiceProvider" --tag="tcb-config"
```

This publishes:

- `config/tweny-blueprint.php` - Main configuration settings

### Step 3: Configure Cache Driver

[](#step-3-configure-cache-driver)

For optimal performance, ensure you're using Redis or Memcached:

```
CACHE_DRIVER=redis
```

### Step 4: Install Dependencies (Optional)

[](#step-4-install-dependencies-optional)

If you want to use all features, install the optional dependencies:

```
# For activity logging
php artisan vendor:publish --provider="Spatie\Activitylog\ActivitylogServiceProvider" --tag="activitylog-migrations"
php artisan migrate

# For permissions
php artisan vendor:publish --provider="Spatie\Permission\PermissionServiceProvider"
php artisan migrate

# For SweetAlert
php artisan vendor:publish --provider="RealRashid\SweetAlert\SweetAlertServiceProvider"

# For Blade Morph (smooth UI transitions)
php artisan vendor:publish --provider="TwenyCode\BladeMorph\BladeMorphServiceProvider"

# For Log Viewer
# Access logs at /log-viewer route

# For Authentication Logging
php artisan vendor:publish --provider="Rappasoft\LaravelAuthenticationLog\LaravelAuthenticationLogServiceProvider"
php artisan migrate
```

Configuration
-------------

[](#configuration)

### Basic Configuration

[](#basic-configuration)

Edit `config/tweny-blueprint.php`:

```
return [
    // Cache Configuration
    'cache' => [
        'enabled' => env('BLUEPRINT_CACHE_ENABLED', true),
        'ttl' => env('BLUEPRINT_CACHE_TTL', 3600), // 1 hour
        'driver' => env('CACHE_DRIVER', 'redis'),
    ],

    // Model Observers
    'observers' => [
        'enabled' => env('BLUEPRINT_OBSERVERS_ENABLED', true),
        'models' => [
            App\Models\User::class,
            App\Models\Post::class,
            // Add your models here
        ],
    ],

    // Authorization
    'authorization' => [
        'enabled' => env('BLUEPRINT_AUTHORIZATION_ENABLED', true),
        'super_admin_role' => env('BLUEPRINT_SUPER_ADMIN_ROLE', 'superAdmin'),
    ],

    // Pagination
    'pagination' => [
        'per_page' => env('BLUEPRINT_PER_PAGE', 15),
        'max_per_page' => 100,
    ],

    // HashIDs Configuration
    'hashids' => [
        'default' => 'main',
        'connections' => [
            'main' => [
                'salt' => env('HASHIDS_SALT', env('APP_KEY')),
                'length' => 6,
                'alphabet' => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890',
            ],
        ],
    ],
];
```

### Environment Variables

[](#environment-variables)

Add to your `.env` file:

```
# Cache Configuration
BLUEPRINT_CACHE_ENABLED=true
BLUEPRINT_CACHE_TTL=3600
CACHE_DRIVER=redis

# Observers
BLUEPRINT_OBSERVERS_ENABLED=true

# Authorization
BLUEPRINT_AUTHORIZATION_ENABLED=true
BLUEPRINT_SUPER_ADMIN_ROLE=superAdmin

# Pagination
BLUEPRINT_PER_PAGE=15

# HashIDs (for integer ID obfuscation)
HASHIDS_SALT="${APP_KEY}"
```

Architecture Overview
---------------------

[](#architecture-overview)

Laravel Blueprint follows a clean architecture pattern with clear separation of concerns:

```
┌─────────────────────────────────────────┐
│           Controllers                    │
│  (Handle HTTP & Route Logic)            │
└──────────────┬──────────────────────────┘
               │
               ▼
┌─────────────────────────────────────────┐
│            Services                      │
│  (Business Logic & Transactions)         │
└──────────────┬──────────────────────────┘
               │
               ▼
┌─────────────────────────────────────────┐
│          Repositories                    │
│  (Data Access & Caching)                 │
└──────────────┬──────────────────────────┘
               │
               ▼
┌─────────────────────────────────────────┐
│            Models                        │
│  (Eloquent ORM & Relationships)          │
└─────────────────────────────────────────┘

```

### Layer Responsibilities

[](#layer-responsibilities)

**Controllers**:

- Handle HTTP requests
- Validate input (via Form Requests)
- Call service methods
- Return views or JSON responses

**Services**:

- Implement business logic
- Manage database transactions
- Coordinate multiple repositories
- Handle complex operations

**Repositories**:

- Abstract data access
- Manage caching
- Query optimization
- CRUD operations

**Models**:

- Define database structure
- Manage relationships
- Provide accessors/mutators
- Implement model events

ID Management Approaches
------------------------

[](#id-management-approaches)

Laravel Blueprint supports two approaches for handling model IDs. Choose the one that best fits your application's needs:

### 🔢 **Option 1: Hashed Integer IDs (Traditional)**

[](#-option-1-hashed-integer-ids-traditional)

Perfect for obfuscating sequential database IDs while maintaining integer performance.

**Advantages:**

- Smaller URL parameters
- Better database performance with integer indexes
- Easier debugging (can decode IDs)
- Lower storage requirements

**Disadvantages:**

- Sequential IDs can be guessed (even when hashed)
- Requires encoding/decoding overhead
- Limited security benefits

**When to use:**

- Working with existing integer-based systems
- Performance is critical for large datasets
- Sequential ID exposure is a minor concern
- Need smaller URL parameters

**Example:**

```
Original ID: 123
Hashed ID: xR9kL2
URL: /users/xR9kL2

```

### 🔑 **Option 2: Native Laravel UUIDs (Recommended)**

[](#-option-2-native-laravel-uuids-recommended)

Ideal for distributed systems, enhanced security, and when you need globally unique identifiers.

**Advantages:**

- Globally unique (no collisions)
- Non-sequential (harder to guess)
- Better security for public APIs
- Works well in distributed systems
- Can be generated offline

**Disadvantages:**

- Larger URLs (36 characters)
- Slightly slower than integer indexes
- More storage space required
- Harder to read/debug

**When to use:**

- Building new applications
- Enhanced security is paramount
- Working with distributed systems or microservices
- Need offline ID generation capability
- Building public APIs where ID exposure matters
- Multi-tenant applications

**Example:**

```
UUID: 550e8400-e29b-41d4-a716-446655440000
URL: /users/550e8400-e29b-41d4-a716-446655440000

```

### Comparison Table

[](#comparison-table)

FeatureHashed Integer IDsNative UUIDsURL LengthShort (6-8 chars)Long (36 chars)PerformanceFasterSlightly slowerSecurityModerateHighGuessableSomewhatNoGlobal UniquenessNoYesStorage4-8 bytes16 bytesReadabilityGoodPoorDistributionCentralizedDistributed---

Quick Start Guide
-----------------

[](#quick-start-guide)

### Using Hashed Integer IDs

[](#using-hashed-integer-ids)

#### 1. Create a Model

[](#1-create-a-model)

```
