iftydev/dynamic-crud 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

iftydev/dynamic-crud

最新稳定版本:v1.0.0

Composer 安装命令:

composer require iftydev/dynamic-crud

包简介

A dynamic CRUD package for Laravel with Repository Pattern and Interface

README 文档

README

Latest Version License

A powerful, production-ready Laravel package that provides dynamic CRUD operations for any Eloquent model using the Repository Pattern with Interface.

✨ Features

  • 🎯 Dynamic CRUD - Works with any Eloquent model
  • 🏗️ Repository Pattern - Clean architecture with Interface/Contract
  • 🔒 Secure - Model whitelist and validation
  • 📄 API-Based - RESTful JSON API endpoints
  • 🔍 Advanced Filtering - Search, range, IN/NOT IN, NULL checks
  • 📊 Pagination - Built-in pagination support
  • 🚀 Eager Loading - Optimize queries with relations
  • 🎨 Extensible - Easy to customize and extend
  • Laravel 9/10/11 - Compatible with latest Laravel versions

📦 Installation

Install the package via Composer:

composer require iftydev/dynamic-crud

The package will automatically register itself via Laravel's package auto-discovery.

Publish Configuration (Optional)

php artisan vendor:publish --tag=dynamic-crud-config

This will create a config/dynamic-crud.php file where you can customize the package behavior.

🚀 Quick Start

Basic Usage

Once installed, you can immediately start using the dynamic CRUD API:

# Get all users
GET /api/dynamic-crud/User

# Get a specific user
GET /api/dynamic-crud/User/1

# Create a new user
POST /api/dynamic-crud/User
{
    "name": "John Doe",
    "email": "john@example.com"
}

# Update a user
PUT /api/dynamic-crud/User/1
{
    "name": "Jane Doe"
}

# Delete a user
DELETE /api/dynamic-crud/User/1

📚 API Endpoints

List All Records

GET /api/dynamic-crud/{Model}

Query Parameters:

  • per_page - Items per page (default: 15, use 'all' for no pagination)
  • page - Page number
  • sort_by - Field to sort by
  • sort_order - Sort direction (asc/desc)
  • with - Comma-separated relations to eager load
  • search - Search across all searchable fields
  • Any model field for exact filtering

Examples:

# Paginated results
GET /api/dynamic-crud/Post?per_page=20&page=2

# With sorting
GET /api/dynamic-crud/Post?sort_by=created_at&sort_order=desc

# With eager loading
GET /api/dynamic-crud/Post?with=author,comments

# With search
GET /api/dynamic-crud/Post?search=laravel

# With filters
GET /api/dynamic-crud/Post?status=published&category_id=5

# Range filters
GET /api/dynamic-crud/Post?created_at_from=2024-01-01&created_at_to=2024-12-31

# IN filters
GET /api/dynamic-crud/Post?status_in[]=draft&status_in[]=published

# All records (no pagination)
GET /api/dynamic-crud/Post?per_page=all

Get Single Record

GET /api/dynamic-crud/{Model}/{id}

Query Parameters:

  • with - Comma-separated relations to eager load

Example:

GET /api/dynamic-crud/Post/1?with=author,comments,tags

Create Record

POST /api/dynamic-crud/{Model}

Body: JSON object with fillable fields

Example:

POST /api/dynamic-crud/Post
Content-Type: application/json

{
    "title": "My First Post",
    "content": "This is the content",
    "status": "draft",
    "user_id": 1
}

Update Record

PUT /api/dynamic-crud/{Model}/{id}
PATCH /api/dynamic-crud/{Model}/{id}

Body: JSON object with fields to update

Example:

PUT /api/dynamic-crud/Post/1
Content-Type: application/json

{
    "status": "published",
    "published_at": "2024-01-15 10:00:00"
}

Delete Record

DELETE /api/dynamic-crud/{Model}/{id}

Example:

DELETE /api/dynamic-crud/Post/1

Bulk Delete

POST /api/dynamic-crud/{Model}/bulk-delete

Body:

{
    "ids": [1, 2, 3, 4, 5]
}

Get Count

GET /api/dynamic-crud/{Model}/count

Query Parameters: Same as list endpoint (filters apply)

Example:

GET /api/dynamic-crud/Post/count?status=published

🔒 Security

Model Whitelist

For production environments, it's highly recommended to whitelist allowed models in config/dynamic-crud.php:

'allowed_models' => [
    \App\Models\User::class,
    \App\Models\Post::class,
    \App\Models\Comment::class,
],

If the whitelist is empty, all models are allowed (not recommended for production).

Authentication & Authorization

Add authentication middleware in the config:

'route_middleware' => [
    'api',
    'auth:sanctum',  // or 'auth:api'
    'throttle:60,1',
],

For more granular control, you can create custom middleware or policies.

🎨 Programmatic Usage

You can also use the repository pattern directly in your code:

use IftyDev\DynamicCrud\DynamicCrud;
use App\Models\Post;

// Using the helper
$crud = new DynamicCrud();
$repository = $crud->repository(Post::class);

// Or using model instance
$repository = $crud->for(new Post);

// Now use repository methods
$posts = $repository->all(['status' => 'published'], 15);
$post = $repository->find(1);
$newPost = $repository->create(['title' => 'New Post']);
$repository->update(1, ['title' => 'Updated']);
$repository->delete(1);

🔧 Advanced Usage

Custom Repository

Create a custom repository for specific models:

namespace App\Repositories;

use IftyDev\DynamicCrud\Repositories\BaseCrudRepository;

class PostRepository extends BaseCrudRepository
{
    protected function getSearchableFields(): array
    {
        return ['title', 'content', 'excerpt'];
    }
    
    public function findPublished()
    {
        return $this->model->where('status', 'published')->get();
    }
}

Then bind it in the config:

'custom_repositories' => [
    \App\Models\Post::class => \App\Repositories\PostRepository::class,
],

Custom Controller

Extend the base controller for additional functionality:

namespace App\Http\Controllers;

use IftyDev\DynamicCrud\Http\Controllers\CrudController;

class CustomCrudController extends CrudController
{
    protected function validateAndResolveModel(string $modelClass): string
    {
        // Add custom validation logic
        
        return parent::validateAndResolveModel($modelClass);
    }
}

📋 Response Format

All endpoints return consistent JSON responses:

Success Response

{
    "success": true,
    "message": "Records retrieved successfully",
    "data": {
        // Your data here
    }
}

Error Response

{
    "success": false,
    "message": "Error message here",
    "errors": {
        // Validation errors (if applicable)
    }
}

Paginated Response

{
    "success": true,
    "message": "Records retrieved successfully",
    "data": {
        "current_page": 1,
        "data": [...],
        "first_page_url": "...",
        "from": 1,
        "last_page": 5,
        "last_page_url": "...",
        "links": [...],
        "next_page_url": "...",
        "path": "...",
        "per_page": 15,
        "prev_page_url": null,
        "to": 15,
        "total": 75
    }
}

🛠️ Configuration Options

Option Description Default
allowed_models Whitelist of models for CRUD [] (all allowed)
default_per_page Default pagination size 15
max_per_page Maximum pagination size 100
respect_soft_deletes Honor soft deletes true
route_middleware Middleware for routes ['api']
route_prefix Route prefix 'dynamic-crud'
enable_query_logging Log queries for debugging false
custom_repositories Custom repository bindings []

🚀 Future Enhancements

Planned features for future versions:

  • Validation Rules - Built-in validation support
  • Permissions - Integration with Spatie Permission
  • JWT Authentication - JWT support out of the box
  • File Uploads - Handle file uploads in CRUD
  • Export/Import - CSV/Excel export and import
  • Audit Logging - Track all CRUD operations
  • GraphQL Support - GraphQL API alongside REST
  • Caching - Built-in caching layer
  • Rate Limiting - Advanced rate limiting
  • Webhooks - Trigger webhooks on CRUD events

📝 Requirements

  • PHP 8.0 or higher
  • Laravel 9.x, 10.x, or 11.x

📄 License

This package is open-sourced software licensed under the MIT license.

🤝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

👨‍💻 Author

IftyDev

🙏 Support

If you find this package helpful, please consider giving it a ⭐ on GitHub!

统计信息

  • 总下载量: 1
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 0
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-12-14