PHP code example of phpsa / laravel-api-controller

1. Go to this page and download the library: Download phpsa/laravel-api-controller 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/ */

    

phpsa / laravel-api-controller example snippets


	protected $resourceSingle = UserResource::class;
	protected $resourceCollection = UserCollection::class;


public function scopeAgeNull(Builder $builder, $isNull = true){
  $isNull ? $builder->whereNull('age') : $builder->whereNotNull('age');
}

    public function index(Request $request)
    {

        $request->apiFilter('user_id', auth()->id());
        $request->apiFilter('owner_id', 'not_equals', auth()->id());
        $request->apiFilter('age', '>=', 5);
        $request->apiFilter('age', '<=', 10);
        $request->apiInclude(['owner','user']);
        $request->apiAddFields(['x','y','z']);


protected static $allowedScopes = [
  'fullname'
];

[
    'email' => 'equired|numeric',
]

class MyModelResource extends ApiResource
{

 protected static $allowedScopes = [
        'withTrashed',
        'onlyTrashed'
    ];
bash
php artisan vendor:publish --provider="Phpsa\LaravelApiController\ServiceProvider" --tag="config"

protected function getNewQuery(): Builder
    {
        return resolve($this->model())->newQuery();
    }

 public function scopeFilterByRelationGroup(Builder $builder, array $wheres): void
    {
        $where =  collect($wheres)->map(fn ($child) =>
           $this->parseFiltersArray($child)
        )->each(
            fn($group, $key) => $builder->whereHas('Relation', function ($subQ) use ($group, $key) {
                $group->each(
                    fn($filter, $column) => collect($filter)->each(fn($value, $comparison) => $this->buildQuery($column, $comparison, $value, $subQ))
                );
            }
            )
        );

    }
  

  Gate::define(
      'supervises-the-group',
      fn ($user, Group $group) => (int) $user->id === $group->supervisor_id
  );