sgflores/cruder

A comprehensive CRUD service package

Installs: 7

Dependents: 0

Suggesters: 0

Security: 0

Stars: 0

Watchers: 0

Forks: 0

Open Issues: 0

pkg:composer/sgflores/cruder

v1.0.0 2025-12-15 11:50 UTC

This package is auto-updated.

Last update: 2025-12-17 11:40:18 UTC


README

License: MIT PHP Version Laravel Version

A powerful, feature-rich CRUD service package for Laravel applications built on SOLID principles and design patterns. Provides comprehensive database operations with advanced features like caching, query logging, column validation, export capabilities, and more.

๐Ÿš€ Key Features

  • Complete CRUD Operations - Create, Read, Update, Delete with full validation
  • Bulk Operations - Efficient bulk create, update, and delete operations
  • Advanced Filtering & Search - Column-based filtering, sorting, and text search
  • Search Strategy System - Pluggable search strategies for custom search implementations
  • Export Functionality - CSV, JSON, and custom export formats
  • Filter Helpers - One-line helpers for common filter patterns such as between ranges
  • Query Caching - Built-in query caching with configurable lifetime
  • Performance Monitoring - Query logging and slow query detection
  • Column Validation - Secure column validation for all operations
  • Virtual Filters - Safely expose computed filter columns via getCustomFilterColumns()
  • Event System - Extensible event system for custom business logic
  • Trait-Based Configuration - Type-safe, IDE-friendly configuration system
  • Audit Trail - Automatic tracking of record changes (created_by, updated_by, deleted_by)

๐Ÿ“‹ Requirements

  • PHP ^8.1
  • Laravel ^10.0|^11.0|^12.0
  • Illuminate Support ^10.0|^11.0|^12.0
  • Illuminate Database ^10.0|^11.0|^12.0
  • Illuminate Validation ^10.0|^11.0|^12.0
  • Illuminate Pagination ^10.0|^11.0|^12.0

๐Ÿ“ฆ Installation

1. Install via Composer

composer require sgflores/cruder

2. Publish Configuration (Optional)

php artisan vendor:publish --provider="SgFlores\Cruder\CruderServiceProvider" --tag="cruder-config"

3. Service Provider (Auto-discovered)

The package will be automatically discovered by Laravel.

๐ŸŽฏ Quick Start

1. Create Your Service

<?php

namespace App\Services;

use SgFlores\Cruder\BaseCrudService;
use SgFlores\Cruder\Services\EventService;
use SgFlores\Cruder\Services\ValidationService;
use App\Models\User;

class UserService extends BaseCrudService
{
    public function __construct(
        User $user,
        EventService $eventService,
        ValidationService $validationService
    ) {
        parent::__construct($user, $eventService, $validationService);
    }
    
    // Override configuration methods as needed
    public function getDirectTextSearchColumns(): array
    {
        return ['name', 'email'];
    }
    
    public function getDirectFilterableColumns(): array
    {
        return ['status', 'department_id'];
    }
    
    public function getDirectSortableColumns(): array
    {
        return ['name', 'email', 'created_at'];
    }
    
    public function isAuditTrailEnabled(): bool
    {
        return true;
    }
}

๐Ÿ’ก Configuration: The service uses a trait-based configuration system. See CONFIGURATION.md for all available configuration methods and examples.

2. Basic Usage

// Find all users with filtering and pagination
$users = $userService->findAll([
    'search' => 'john',
    'status' => 'active',
    'sort_by' => 'name',
    'sort_direction' => 'asc',
    'per_page' => 10,
    'page' => 1
]);

// Find user by ID and load department relation (resource-aware)
$user = $userService->findById(1, ['department']); // returns Model|JsonResource|null

// Find raw model (no resource transformation) for policy checks
$rawUser = $userService->findByIdRaw(1, ['department']); // returns ?Model

// Create user (returns Model|JsonResource)
$user = $userService->create([
    'name' => 'John Doe',
    'email' => 'john@example.com'
]);

// Update user (returns Model|JsonResource|null)
$user = $userService->update(1, [
    'name' => 'John Smith'
]);

// Delete user
$userService->delete(1);

// Bulk operations
$userService->bulkCreate([
    ['name' => 'User 1', 'email' => 'user1@example.com'],
    ['name' => 'User 2', 'email' => 'user2@example.com']
]);

3. Between Filter Helper

BaseReaderService ships with a convenience helper for assembling range filters without hand-writing the advanced filter structure:

$filters = [
    'created_from' => '2025-01-01',
    'created_to'   => '2025-01-31',
];

$this->mergeBetweenFilter(
    $filters,
    'orders.created_at', // actual database column
    'created_from',      // input key for the lower bound
    'created_to',        // input key for the upper bound
    'Y-m-d'              // optional Carbon format
);

// $filters now contains:
// [
//     'orders.created_at' => [
//         'operator' => 'between',
//         'value'    => ['2025-01-01', '2025-01-31'],
//     ],
// ]

// Resulting SQL fragment
// where `orders`.`created_at` between '2025-01-01' and '2025-01-31'

๐Ÿ“ Note: For export functionality, you'll need to extend BaseReaderService with SearchService and ExportService injected. See Examples/README.md for complete examples.

4. Search Strategies

Create custom search implementations for complex reporting and analytics using the strategy pattern.

Key Features:

  • Custom Search Strategies - Pluggable strategies
  • Query Type Flexibility - Support both Eloquent Builder and QueryBuilder
  • Proper Service Injection - Extend BaseReaderService with SearchService injected

Example Strategy Implementation:

class TopOrdersStrategy implements SearchStrategyInterface
{
    public static function key(): string
    {
        return 'top_orders';
    }
    
    public function search(Builder|QueryBuilder|null $query, array $filters, array $config = []): Builder|QueryBuilder
    {
        return $query->orderBy('total_amount', 'desc');
    }
}

Usage:

// Register strategy
$this->searchService->addStrategy(TopOrdersStrategy::key(), new TopOrdersStrategy());

// Use in queries
$results = $this->findAll(['strategies' => TopOrdersStrategy::key()]);

Complete Example: See Examples/SalesReportService.php for full implementation.

๐Ÿ“š Documentation

๐Ÿ“– Available Examples

Quick Reference:

See Examples/README.md for comprehensive documentation.

๐Ÿงช Testing

composer test              # Run test suite
composer test-coverage     # Run with coverage

๐Ÿค Contributing

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

๐Ÿ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

๐Ÿ‘จโ€๐Ÿ’ป Author

sgflores

๐Ÿ™ Acknowledgments

Built with โค๏ธ for the Laravel community using: