PHP code example of david-chamling / laravel-api-crud

1. Go to this page and download the library: Download david-chamling/laravel-api-crud library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

david-chamling / laravel-api-crud example snippets


Route::crudResource('products', ProductController::class);

// StoreProductRequest.php

public function rules(): array
{
    return [
        'name' => 'ories,id'
    ];
}

// Product.php

protected $fillable = [
    'name',
    'price',
    'category_id',
    // Add additional fields here
];

protected array $searchableColumns = ['name', 'description'];
protected array $searchableRelations = ['category' => ['name']];
protected int $paginationNumber = 15;

public function beforeStore(array $data, Request $request): array
{
    $data['slug'] = Str::slug($data['name']);
    return $data;
}

public function afterStore(Model $model, Request $request): void
{
    // sending Notification, Sms, Creating logs, Storing into relational table
    // example:
    ActivityLog::create([
        'user_id' => $request->user()->id,
        'action' => 'store',
        'model_id' => $model->id,
        'changes' => $model->getChanges(),
    ]);

    if ($model->wasChanged('status')) {
        Notification::send(
            $model->assignedUsers,
            new StatusUpdatedNotification($model)
        );
    }
}

use DavidChamling\LaravelApiCrud\Utilities\ApiResponse;

return ApiResponse::success($data);         // 200 OK
return ApiResponse::created($newModel);     // 201 Created
return ApiResponse::error('Something went wrong'); // 400/500 Error
return ApiResponse::validationError($errors);      // 422 Unprocessable

use DavidChamling\LaravelApiCrud\Controllers\CrudController;
use DavidChamling\LaravelApiCrud\Utilities\ApiResponse;

class ProductController extends CrudController
{
    protected array $searchableColumns = ['name', 'sku'];
    protected array $searchableRelations = [
        'category' => ['name'],
        'manufacturer' => ['name'],
    ];

    public function __construct()
    {
        parent::__construct(
            model: Product::class,
            storeRequest: StoreProductRequest::class,
            updateRequest: UpdateProductRequest::class,
            simpleResource: ProductResource::class,
            detailedResource: ProductDetailResource::class,
            serviceClass: ProductCrudService::class
        );
    }

    public function featured()
    {
        $products = $this->model::featured()->get();
        return ApiResponse::success(ProductResource::collection($products));
    }
}
bash
php artisan vendor:publish --tag=crud-stubs
bash
php artisan make:crud Product