PHP code example of maarsson / eloquent-getter

1. Go to this page and download the library: Download maarsson/eloquent-getter 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/ */

    

maarsson / eloquent-getter example snippets


    namespace App\Models;

    use Maarsson\EloquentGetter\Traits\GetterableTrait;

    class YourModel
    {
        use GetterableTrait;
    }
    

    protected function nameFilter(string|null $searchString): \Illuminate\Database\Eloquent\Builder
    {
        return $this->builder->where('name', 'LIKE', '%' . $searchString . '%');
    }
    

    // HTTP GET //localhost/yourmodel?filter[name]=foo
    public function index(\App\Getters\YourModelGetter $getter)
    {
        return $model
            ->filter($getter)
            ->get();
    }
    

    protected function relatedModelDateSorter(): \Illuminate\Database\Eloquent\Builder
    {
        return RelatedModel::select('date')
            ->whereColumn('this_model_column', 'related_table.column');
    }
    

    // HTTP GET //localhost/yourmodel?sort_by=related_model_date
    public function index(\App\Filters\YourModelGetter $getter)
    {
        return $model
            ->order($getter)
            ->get();
    }
    

// HTTP GET //localhost/yourmodel?filter[name]=foo&page=5&per_page=20&sort_by=related_model_date&sort_order=desc
public function index(\App\Filters\YourModelGetter $getter)
{
    return $model
        ->filter($getter)
        ->order()
        ->paginate();
}

    // HTTP GET //localhost/yourmodel?filter[name]=foo&page=5&per_page=20&sort_by=related_model_date&sort_order=desc
    public function index(\App\Filters\YourModelGetter $getter)
    {
        return $model
            ->filter($getter)
            ->order()
            ->paginate();
            ->through(
                fn ($item) => $item->withAttributes([
                    'id',
                    'name', // a model property
                    'finalPrice', // even a model accessor
                    'users' // a relation (with all of its attributes)
                    'users.posts:id,title', // a relations relation (with limited attributes)
                ])
            );
    }