mdelariva/api-controller

API basic requests control

v1.10.0 2022-10-12 17:10 UTC

This package is auto-updated.

Last update: 2024-05-12 20:49:12 UTC


README

API server CRUDL trait for Laravel controllers.

Actions routes

VerbURIActionRoute NameDescription
GET/{entity}index{entity}.indexListing (filters allowed)
GET/{entity}/{id}show{entity}.showShow full {entity}
POST/{entity}store{entity}.storeCreates new {entity}
PUT/{entity}/{id}update{entity}.updateUpdates {entity}
DELETE/{entity}/{id}destroy{entity}.destroyDeletes {entity}

Naming conventions

  • Model class name: Entity
  • Controllers class name: EntityController
  • Resource class name: EntityResource

Validations

Every model must have 2 public static methods:

  • getValidations() must return an array where each item's key is a field name, and the value is the validation rules (Illuminate\Validation\Validator).
  • getValidationsRequired() must return an array of required field names.

Example

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Example extends Model
{
    protected $fillable = [
        'name',
        'code',
    ];

    // validations

    public static function getValidations()
    {
        $validations = [
            'name'         => 'string|between:5,255',
            'code'         => 'string|size:2',
        ];
        return $validations;
    }

    public static function getValidationsRequired()
    {
        $validationsRequired = [
            'name',
            'code',
        ];
        return $validationsRequired;
    }
}

Index listing

Request parameters available

  • where[] . Valid operators (appended to field name):

    • {fieldName} => field = value
    • {fieldName}[] => field IN (value)
    • {fieldName}_gt => field > value
    • {fieldName}_ge => field >= value
    • {fieldName}_lt => field < value
    • {fieldName}_le => field <= value
    • {fieldName}_ct => field like "%value%"
    • {fieldName}_pr => field like "value%"
    • {fieldName}_ap => field like "%value"
  • orderBy

  • orderByDir
  • limit (-1 to get all records; default=20)

Properties

You can declare the following properties in the controller:

NameDefault valueTypeDescription
limitAmount20intAmount of records to return.
indexDefaultOrderBystringField to sort by
indexDefaultOrderByDirstringDirection to sort by (asc or desc)
modelGenerates name using name conventionsstringName of the class of the model
modelPath\App\Models\stringPath to the class of the model
resourceGenerates name using name conventionsstringName of the class of the resource
resourcePath\App\Http\Resources\stringPath to the class of the resource

Hooks

All hook types must be defined in MdelaRiva\ApiRequests\Libraries\Hook\HookType class.

ActionNameParams
InitBefore
InitAfter
indexIndexBefore\Illuminate\Http\Request
indexIndexPreRun\Illuminate\Database\Eloquent\Builder
indexIndexAfterbool, \Illuminate\Database\Eloquent\Model
storeStoreBefore\Illuminate\Http\Request
storeStoreAfterbool, \Illuminate\Database\Eloquent\Model
updateUpdateBefore\Illuminate\Http\Request
updateUpdateAfterbool, \Illuminate\Database\Eloquent\Model
destroyDeleteBefore\Illuminate\Database\Eloquent\Model
destroyDeleteAfterint

Usage example

Laravel

1- Define API resouces route in routes/api.php

<?php

Route::apiResource( 'articles', 'ArticleController' );

2- Define model validations app/Models/Article.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Article extends Model
{
    protected $fillable = [
        'name',
        'code',
    ];

    public static function getValidations()
    {
        $validations = [
            'name'         => 'string|between:5,255',
            'code'         => 'string|size:2',
        ];
        return $validations;
    }

    public static function getValidationsRequired()
    {
        $validationsRequired = [
            'name',
            'code',
        ];
        return $validationsRequired;
    }
}

3- Define controller app/Http/Controllers/ArticleController.php

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use MdelaRiva\ApiRequests\ApiBaseRequests;
use MdelaRiva\ApiRequests\Libraries\Hook\Hook;
use MdelaRiva\ApiRequests\Libraries\Hook\HookType;
use App\Models\ArticleThirdParty;
use App\Http\Resources\ArticleThirdPartyResource;

class ArticleController extends Controller
{
    use ApiBaseRequests;

    /**
     * ApiBaseRequests: Index - Order by
     *
     * @var string
     */
    protected $indexDefaultOrderBy = 'name';

    /**
     * ApiBaseRequests: Index - Order by direction (ASC, DESC)
     *
     * @var string
     */
    protected $indexDefaultOrderByDir = 'desc';
    
    /**
     * ApiBaseRequests: Hooks register
     *
     * @var string
     */
    protected function registerApiHooks(){
        Hook::register( HookType::IndexBefore, function(){
            $this->model = ArticleThirdParty::class;
            $this->resource = ArticleThirdPartyResource::class;
        } );

        Hook::register( HookType::IndexPreRun, function( $query ){
            $query->groupBy( 'party_id' );
        } );
    }
}

4- Make request