All Projects → awes-io → Repository

awes-io / Repository

Licence: mit
🖖Repository Pattern in Laravel. The package allows to filter by request out-of-the-box, as well as to integrate customized criteria and any kind of filters.

Projects that are alternatives of or similar to Repository

Config
Manage Laravel configuration by persistent storage
Stars: ✭ 139 (+3.73%)
Mutual labels:  laravel, repository
Nova Mega Filter
Allows you to control the columns and filters shown on any Nova resource index
Stars: ✭ 49 (-63.43%)
Mutual labels:  laravel, filters
receptacle
minimalistic implementation of the repository pattern
Stars: ✭ 18 (-86.57%)
Mutual labels:  repository, pattern
Warehouse
Artesãos Warehouse - A simple and direct approach to repositories!
Stars: ✭ 87 (-35.07%)
Mutual labels:  laravel, repository
Laravel Repositories
[ABANDONED] Rinvex Repository is a simple, intuitive, and smart implementation of Active Repository with extremely flexible & granular caching system for Laravel, used to abstract the data layer, making applications more flexible to maintain.
Stars: ✭ 664 (+395.52%)
Mutual labels:  laravel, repository
Laravel Repository
Repository Design Pattern for Laravel 5 with Eloquent or Collection
Stars: ✭ 109 (-18.66%)
Mutual labels:  laravel, repository
Hyrax
Hyrax is a Ruby on Rails Engine built by the Samvera community. Hyrax provides a foundation for creating many different digital repository applications.
Stars: ✭ 131 (-2.24%)
Mutual labels:  repository
Laravel Coreui Vue
Laravel 5.6 with CoreUI (VueJS Full Starter Template) >>> Deprecated, please go to https://coreui.io/laravel/
Stars: ✭ 132 (-1.49%)
Mutual labels:  laravel
Nova Slug Field
Slug field for Laravel Nova
Stars: ✭ 131 (-2.24%)
Mutual labels:  laravel
Laragym
A laravel gym management system
Stars: ✭ 130 (-2.99%)
Mutual labels:  laravel
Release Belt
Composer repository implementation for ZIPs.
Stars: ✭ 133 (-0.75%)
Mutual labels:  repository
Laravel Emojione
Laravel package to make it easy to use the gorgeous emojis from EmojiOne
Stars: ✭ 133 (-0.75%)
Mutual labels:  laravel
Multi Auth
Laravel Multi-Authentication Package
Stars: ✭ 131 (-2.24%)
Mutual labels:  laravel
Laravel Governor
Manage authorization with granular role-based permissions in your Laravel Apps.
Stars: ✭ 131 (-2.24%)
Mutual labels:  laravel
Laravel Getting Started
本文介绍如何开始使用 Laravel !
Stars: ✭ 132 (-1.49%)
Mutual labels:  laravel
Health
Laravel Health Panel
Stars: ✭ 1,774 (+1223.88%)
Mutual labels:  laravel
Menus
📌 Menu generator package for the Laravel framework
Stars: ✭ 133 (-0.75%)
Mutual labels:  laravel
Nova Settings Tool
Laravel Nova tool to view and edit application settings.
Stars: ✭ 131 (-2.24%)
Mutual labels:  laravel
Laravel Seo
SEO package made for maximum customization and flexibility
Stars: ✭ 130 (-2.99%)
Mutual labels:  laravel
Laravel cities
Find any country/city in the world. Get Long/Lat etc. Deploy geonames.org database localy. Optimized DB tree
Stars: ✭ 133 (-0.75%)
Mutual labels:  laravel

Awes.io logo

Repository

Repository Pattern in Laravel. The package allows to filter by request out-of-the-box, as well as to integrate customized criteria and any kind of filters.

Coverage report Last version Build status Downloads License CDN Ready laravel Last commit Analytics Hosted by Package Kit Patreon

Repository Laravel

Table of Contents

Installation

Via Composer

$ composer require awes-io/repository

The package will automatically register itself.

Configuration

First publish config:

php artisan vendor:publish --provider="AwesIO\Repository\RepositoryServiceProvider" --tag="config"
// $repository->smartPaginate() related parameters
'smart_paginate' => [
    // name of request parameter to take paginate by value from
    'request_parameter' => 'limit',
    // default paginate by value
    'default_limit' => 15,
    // max paginate by value
    'max_limit' => 100,
]

Overview

Package allows you to filter data based on incoming request parameters:
https://example.com/news?title=Title&custom=value&orderBy=name_desc

It will automatically apply built-in constraints onto the query as well as any custom scopes and criteria you need:

protected $searchable = [
    // where 'title' equals 'Title'
    'title',
];

protected $scopes = [
    // and custom parameter used in your scope
    'custom' => MyScope::class,
];
class MyScope extends ScopeAbstract
{
    public function scope($builder, $value, $scope)
    {
        return $builder->where($scope, $value)->orWhere(...);
    }
}

Ordering by any field is available:

protected $scopes = [
    // orderBy field
    'orderBy' => OrderByScope::class,
];

Package can also apply any custom criteria:

return $this->news->withCriteria([
    new MyCriteria([
        'category_id' => '1', 'name' => 'Name'
    ])
    ...
])->get();

Usage

Create a Model

Create your model:

namespace App;

use Illuminate\Database\Eloquent\Model;

class News extends Model 
{
    ...
}

Create a Repository

Extend it from AwesIO\Repository\Eloquent\BaseRepository and provide entity() method to return full model class name:

namespace App;

use AwesIO\Repository\Eloquent\BaseRepository;

class NewsRepository extends BaseRepository
{
    public function entity()
    {
        return News::class;
    }
}

Use built-in methods

use App\NewsRepository;

class NewsController extends BaseController 
{
    protected $news;

    public function __construct(NewsRepository $news)
    {
        $this->news = $news;
    }
    ....
}

Execute the query as a "select" statement or get all results:

$news = $this->news->get();

Execute the query and get the first result:

$news = $this->news->first();

Find a model by its primary key:

$news = $this->news->find(1);

Add basic where clauses and execute the query:

$news = $this->news->->findWhere([
        // where id equals 1
        'id' => '1',
        // other "where" operations
        ['news_category_id', '<', '3'],
        ...
    ]);

Paginate the given query:

$news = $this->news->paginate(15);

Paginate the given query into a simple paginator:

$news = $this->news->simplePaginate(15);

Paginate the given query by 'limit' request parameter:

$news = $this->news->smartPaginate();

Add an "order by" clause to the query:

$news = $this->news->orderBy('title', 'desc')->get();

Save a new model and return the instance:

$news = $this->news->create($request->all());

Update a record:

$this->news->update($request->all(), $id);

Delete a record by id:

$this->news->destroy($id);

Attach models to the parent:

$this->news->attach($parentId, $relationship, $idsToAttach);

Detach models from the relationship:

$this->news->detach($parentId, $relationship, $idsToDetach);

Find model or throw an exception if not found:

$this->news->findOrFail($id);

Execute the query and get the first result or throw an exception:

$this->news->firstOrFail();

Create a Criteria

Criteria are a way to build up specific query conditions.

use AwesIO\Repository\Contracts\CriterionInterface;

class MyCriteria implements CriterionInterface {

    protected $conditions;
    
    public function __construct(array $conditions)
    {
        $this->conditions = $conditions;
    }

    public function apply($entity)
    {
        foreach ($this->conditions as $field => $value) {
            $entity = $entity->where($field, '=', $value);
        }
        return $entity;
    }
}

Multiple Criteria can be applied:

use App\NewsRepository;

class NewsController extends BaseController 
{
    protected $news;

    public function __construct(NewsRepository $news)
    {
        $this->news = $news;
    }

    public function index()
    {
        return $this->news->withCriteria([
            new MyCriteria([
                'category_id' => '1', 'name' => 'Name'
            ]),
            new WhereAdmin(),
            ...
        ])->get();
    }
}

Scope, Filter and Order

In your repository define which fields can be used to scope your queries by setting $searchable property.

protected $searchable = [
    // where 'title' equals parameter value
    'title',
    // orWhere equals
    'body' => 'or',
    // where like
    'author' => 'like',
    // orWhere like
    'email' => 'orLike',
];

Search by searchables:

public function index($request)
{
    return $this->news->scope($request)->get();
}
https://example.com/news?title=Title&body=Text&author=&email=gmail

Also several serchables enabled by default:

protected $scopes = [
    // orderBy field
    'orderBy' => OrderByScope::class,
    // where created_at date is after
    'begin' => WhereDateGreaterScope::class,
    // where created_at date is before
    'end' => WhereDateLessScope::class,
];
$this->news->scope($request)->get();

Enable ordering for specific fields by adding $orderable property to your model class:

public $orderable = ['email'];
https://example.com/news?orderBy=email_desc&begin=2019-01-24&end=2019-01-26

orderBy=email_desc will order by email in descending order, orderBy=email - in ascending

You can also build your own custom scopes. In your repository override scope() method:

public function scope($request)
{
    // apply build-in scopes
    parent::scope($request);

    // apply custom scopes
    $this->entity = (new NewsScopes($request))->scope($this->entity);

    return $this;
}

Create your scopes class and extend ScopesAbstract

use AwesIO\Repository\Scopes\ScopesAbstract;

class NewsScopes extends ScopesAbstract
{
    protected $scopes = [
        // here you can add field-scope mappings
        'field' => MyScope::class,
    ];
}

Now you can build any scopes you need:

use AwesIO\Repository\Scopes\ScopeAbstract;

class MyScope extends ScopeAbstract
{
    public function scope($builder, $value, $scope)
    {
        return $builder->where($scope, $value);
    }
}

Artisan Commands

Package provides useful artisan command:

php artisan repository:generate Models/Order --scope=Search

It'll generate several classes for App\Models\Order:

Main repository: App\Repositories\Orders\OrdersRepository

Main scopes class: App\Repositories\Orders\Scopes\OrdersScopes

Individual search scope class: App\Repositories\Orders\Scopes\SearchOrdersScope

Testing

The coverage of the package is Coverage report.

You can run the tests with:

composer test

Contributing

Please see contributing.md for details and a todolist.

Credits

License

MIT

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].