gridprinciples/repository

There is no license information available for the latest version (0.1.1) of this package.

0.1.1 2015-11-18 06:08 UTC

This package is not auto-updated.

Last update: 2024-12-21 20:46:52 UTC


README

A basic Eloquent Repository for Laravel 5.1.

Installation

  1. Run composer require gridprinciples/repository from your project directory.

  2. Add the following to the providers array in config/app.php:

    GridPrinciples\Repository\RepositoryServiceProvider::class,
  3. Make a Repositories folder somewhere in your application, such as app/Repositories.

Usage

  1. Make a new Repository by extending GridPrinciples\Repository:

    <?php
    
    namespace App\Repositories;
    
    use GridPrinciples\EloquentRepository;
    
    class FooRepository extends EloquentRepository {
        protected static $model = \App\Foo::class;
    }
  2. (Recommended) Use your repository in your controller(s):

    <?php
    
    namespace App\Http\Controllers;
    
    use App\Repositories\FooRepository;
    
    public function __construct(FooRepository $repository)
    {
        $this->repository = $repository;
    }
    
    public function somePage($id)
    {
        $model = $this->repository->get($id);
    
        if(!$model) {
            // Model not found.
            return abort(404);
        }
    
        return view('my_view', [
            'foo' => $model,
        ]);
    }

Some basic CRUD functionality is included with the EloquentRepository:

Creating

You can call save with an array of data in order to make a new model/record.

$newModel = $this->repository->save([
    'title' => 'This is indicative of a title',
    'description' => 'You might have a description field, perhaps.',
]);

It is recommended you populate your model's $fillable array in order to avoid mass-assignment problems.

Reading

You can select one or many records by their keys (usually id) using get:

$singleModel = $this->repository->get(1);
$multipleModels = $this->repository->get([2, 3, 4]);

If you'd like to retrieve many models and paginate them, use the index method:

$pageOfModels = $this->repository->index(10); // 10 records per page

Updating

You can update models in a very similar way as creating, also by using the save method:

$data = [
    'status' => 'active',
];
$id = 1;

$this->repository->save($data, $id);

You can also pass an array of keys as the second argument to save in order to update many records at once.

Deleting

Deleting models can be accomplished easily using the delete method:

$this->repository->delete($id);

You can also pass an array of keys to delete in order to delete many records at once.

License

This is open-sourced software licensed under the MIT license.