Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Crud Api Laravel Package

rizkussef/laravel-crud-api

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require rizkussef/laravel-crud-api
    

    Publish the config:

    php artisan vendor:publish --provider="RizkUssef\CrudApi\CrudApiServiceProvider"
    
  2. Basic CRUD Endpoint Define a model (e.g., Post) and generate a CRUD controller:

    php artisan make:crud Post
    

    This creates:

    • app/Http/Controllers/Api/V1/PostCrudController.php
    • A corresponding route in routes/api.php:
      Route::apiResource('posts', \App\Http\Controllers\Api\V1\PostCrudController::class);
      
  3. First Request Test the API with:

    curl -X GET http://your-app.test/api/v1/posts
    

    Returns a paginated list of Post resources.


Key First-Use Features

  • Automatic Resource Resolution: No manual Resource class needed (uses JsonResource by default).
  • Eager-Loading: Relationships are auto-loaded via with() in the controller.
  • Filtering: Built-in support for query filtering (e.g., ?filter[status]=published).

Implementation Patterns

Workflow: Building a Feature

  1. Define Model & Relationships

    // app/Models/Post.php
    public function author()
    {
        return $this->belongsTo(User::class);
    }
    
  2. Extend the Controller Override methods in PostCrudController:

    protected function getQuery()
    {
        return Post::with('author')->where('status', 'published');
    }
    
    public function store(Request $request)
    {
        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'content' => 'required|string',
        ]);
        return parent::store($validated);
    }
    
  3. Custom Filtering Add a filter in app/Providers/CrudApiServiceProvider.php:

    public function boot()
    {
        CrudApi::addFilter('posts', 'category', function ($query, $value) {
            return $query->where('category_id', $value);
        });
    }
    

    Use it via:

    curl -X GET "http://your-app.test/api/v1/posts?filter[category]=1"
    

Integration Tips

  • API Versioning: The package supports versioning via api/v1 routes by default. Extend with:

    Route::prefix('api/v2')->group(function () {
        Route::apiResource('posts', \App\Http\Controllers\Api\V2\PostCrudController::class);
    });
    
  • Custom Responses Override toArray() in your model or use a custom resource:

    public function toArray()
    {
        return [
            'id' => $this->id,
            'title' => $this->title,
            'slug' => Str::slug($this->title),
        ];
    }
    
  • Authorization Use Laravel’s gates/policies within controller methods:

    public function update(Request $request, $id)
    {
        $this->authorize('update', Post::findOrFail($id));
        return parent::update($request, $id);
    }
    
  • Testing Mock the controller in tests:

    $response = $this->getJson('/api/v1/posts');
    $response->assertStatus(200)->assertJsonStructure([...]);
    

Gotchas and Tips

Pitfalls

  1. Route Caching After adding new routes, clear the route cache:

    php artisan route:clear
    

    (Avoids Route [posts.store] not defined errors.)

  2. Mass Assignment The package does not auto-sanitize input. Always validate in store()/update():

    $validated = $request->validate([
        'title' => 'required',
        'author_id' => 'exists:users,id',
    ]);
    
  3. Relationship Loading Eager-loading is not automatic for nested relationships. Explicitly define:

    protected function getQuery()
    {
        return Post::with(['author', 'comments.user']);
    }
    
  4. Pagination Defaults The package uses Laravel’s default pagination (15 items). Override in getQuery():

    return Post::paginate(10);
    

Debugging

  • Enable Query Logging Add to config/app.php:

    'debug' => env('APP_DEBUG', true),
    

    Check logs in storage/logs/laravel.log for raw queries.

  • Filter Validation Filters are not validated by default. Add middleware or use Laravel’s Rule:

    CrudApi::addFilter('posts', 'status', function ($query, $value) {
        $query->where('status', $value);
        return $query;
    });
    

Extension Points

  1. Custom Actions Add methods to the controller and define routes:

    // Controller
    public function publish($id)
    {
        $post = Post::findOrFail($id);
        $post->update(['status' => 'published']);
        return response()->json(['message' => 'Published!']);
    }
    
    // Route
    Route::put('posts/{id}/publish', [PostCrudController::class, 'publish']);
    
  2. Dynamic Fields Use fillable or guarded in the model, but always validate in the controller.

  3. Event Hooks Listen for CRUD events in EventServiceProvider:

    CrudApi::on('posts.created', function ($post) {
        // Send notification, etc.
    });
    
  4. API Documentation Integrate with Laravel API Docs or Postman by documenting:

    • Base URL: /api/v1/posts
    • Query params: ?filter[field]=value&include=relationships
    • Example payloads for POST/PUT.
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle