1. Go to this page and download the library: Download maarsson/laravel-repository 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 / laravel-repository example snippets
'models' => [
'YourModel',
],
use App\Interfaces\YourModelRepositoryInterface;
class TestController extends Controller
{
private $repository;
public function __construct(YourModelRepositoryInterface $repository)
{
$this->repository = $repository;
}
}
class YourModelRepository extends AbstractEloquentRepository implements YourModelRepositoryInterface
{
public function doSomeConverting()
{
// your code here
}
}
interface YourModelRepositoryInterface
{
public function doSomeConverting();
}
// simple pagination
$this->repository
->paginate($per_page = 15);
// pagination on ordered result
$this->repository
->orderBy('name')
->paginate($per_page = 15);
namespace App\Repositories;
use Maarsson\Repository\Traits\GetterableTrait;
class YourModelRepository extends AbstractEloquentRepository implements CustomerRepositoryInterface
{
use GetterableTrait;
}
// HTTP GET //localhost/yourmodel?filter[name]=foo
public function index(\App\Filters\YourModelGetter $getter)
{
return $this->repository
->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 $this->repository
->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 $this->repository
->filter($getter)
->order()
->paginate();
}
namespace App\Models;
use Maarsson\Repository\Traits\EloquentAttributeFilterTrait;
class YourModel extends Model
{
use EloquentAttributeFilterTrait;
}
// 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 $this->repository
->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)
])
);
}