PHP code example of nvmcommunity / laravel-eloquent-api
1. Go to this page and download the library: Download nvmcommunity/laravel-eloquent-api 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' );
nvmcommunity / laravel-eloquent-api example snippets
use Nvmcommunity \Alchemist \RestfulApi \Common \Exceptions \AlchemistRestfulApiException ;
use Nvmcommunity \Alchemist \RestfulApi \Common \Integrations \AlchemistQueryable ;
use Nvmcommunity \Alchemist \RestfulApi \FieldSelector \Handlers \FieldSelector ;
use Nvmcommunity \Alchemist \RestfulApi \ResourceFilter \Handlers \ResourceFilter ;
use Nvmcommunity \Alchemist \RestfulApi \ResourceFilter \Objects \FilteringRules ;
use Nvmcommunity \Alchemist \RestfulApi \ResourcePaginations \OffsetPaginator \Handlers \ResourceOffsetPaginator ;
use Nvmcommunity \Alchemist \RestfulApi \ResourceSearch \Handlers \ResourceSearch ;
use Nvmcommunity \Alchemist \RestfulApi \ResourceSort \Handlers \ResourceSort ;
class UserApiQuery extends AlchemistQueryable
{
public static function fieldSelector (FieldSelector $fieldSelector) : void
{
$fieldSelector->defineFieldStructure([
'id' , 'name' , 'email' , 'created_at'
])
->defineDefaultFields(['id' ]);
}
public static function resourceFilter (ResourceFilter $resourceFilter) : void
{
$resourceFilter->defineFilteringRules([
FilteringRules::String('id' , ['eq' ]),
FilteringRules::String('name' , ['eq' , 'contains' ]),
FilteringRules::String('email' , ['eq' , 'contains' ]),
FilteringRules::Datetime('created_at' , ['eq' , 'gte' , 'lte' , 'between' ]),
]);
}
public static function resourceOffsetPaginator (ResourceOffsetPaginator $resourceOffsetPaginator) : void
{
$resourceOffsetPaginator->defineDefaultLimit(10 )
->defineMaxLimit(1000 );
}
public static function resourceSearch (ResourceSearch $resourceSearch) : void
{
$resourceSearch->defineSearchCondition('name' );
}
public static function resourceSort (ResourceSort $resourceSort) : void
{
$resourceSort->defineDefaultSort('id' )
->defineDefaultDirection('desc' )
->defineSortableFields(['id' , 'name' ]);
}
}
use App \Models \User ;
use Illuminate \Http \JsonResponse ;
use Illuminate \Http \Request ;
use Nvmcommunity \Alchemist \RestfulApi \Common \Exceptions \AlchemistRestfulApiException ;
use Nvmcommunity \EloquentApi \EloquentBuilder ;
class UserController extends Controller
{
public function index (Request $request, JsonResponse $response) : JsonResponse
{
$eloquentBuilder = EloquentBuilder::for(User::class, UserApiQuery::class, $request->input());
if (! $eloquentBuilder->validate($e)->passes()) {
return $response->setData($e->getErrors())->setStatusCode(400 );
}
return $response->setData($eloquentBuilder->getBuilder()->get());
}
}