PHPackages                             dannyweeks/laravel-base-repository - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. dannyweeks/laravel-base-repository

ActiveLibrary[Database &amp; ORM](/categories/database)

dannyweeks/laravel-base-repository
==================================

An abstract repository class for your Eloquent repositories that requires minimal config to get started.

v1.0(10y ago)202.0k8[2 issues](https://github.com/dannyweeks/laravel-base-repository/issues)MITPHP

Since Oct 24Pushed 8y ago2 watchersCompare

[ Source](https://github.com/dannyweeks/laravel-base-repository)[ Packagist](https://packagist.org/packages/dannyweeks/laravel-base-repository)[ RSS](/packages/dannyweeks-laravel-base-repository/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (2)Dependencies (5)Versions (3)Used By (0)

Laravel Base Repository
=======================

[](#laravel-base-repository)

[![Build Status](https://camo.githubusercontent.com/b9a288ab2cfbaad9166362095565a046b4f5371894536f01aa19466bb6182f56/68747470733a2f2f7472617669732d63692e6f72672f64616e6e797765656b732f6c61726176656c2d626173652d7265706f7369746f72792e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/dannyweeks/laravel-base-repository)

An abstract repository class for your Eloquent repositories that requires minimal config to get started.

Features
--------

[](#features)

- 2 minute setup.
- 10 useful methods out of the box such as `getById`.
- Flexible relationship support including eager loading..
- Optional easy to use Caching.
- Optional 404 exceptions when items aren't found.

Quick Start
-----------

[](#quick-start)

Install via [Composer](http://getcomposer.org).

`composer require dannyweeks/laravel-base-repository`

Extend your repositories with `Weeks\Laravel\Repositories\BaseEloquentRepository`.

Add the `$model` property to your repository so the base repository knows what model to use.

```
    namespace App\Repositories;

    class PostRepository extends \Weeks\Laravel\Repositories\BaseEloquentRepository
    {
        protected $model = \App\Models\Post::class;
    }
```

That's it! Let's test it out.

```
    $repo = new App\Repositories\PostRepository();
    var_dump($repo->getById(1)); // Returns the Post with an ID of 1.
    var_dump($repo->getAll()); // Returns a collection of all your posts.
```

Usage
-----

[](#usage)

Your repositories must extend the `BaseEloquentRepository` class and have the properties:

- `protected $model`: the name of your model (including it's namespace)
- `protected $relationships`: (Optional) an array of the methods available to be included when retrieving items.

```
    $posts = new App\Repositories\PostRepository();
    $firstPost = $posts->getById(1);
    $allPosts = $posts->getAll();
    $allPostsIncludingComments = $posts->with('comments')->getAll();
```

Be sure to check out the [example](#an-example).

Available Methods
-----------------

[](#available-methods)

See the [repository interface](https://github.com/dannyweeks/laravel-base-repository/blob/master/src/RepositoryContract.php) class for the full API.

Relationships
-------------

[](#relationships)

Relationships are defined in the repository but are not eagerly loaded automatically.

Relationships can be loaded in the following three ways using the `with()` method:

- `$postRepository->with('all')->getAll(); ` retrieve all relationships defined in the repository class
- `$postRepository->with(['comments', 'author'])->getAll(); ` retrieve relationships using an array
- `$postRepository->with('comments')->getAll(); ` retrieve relationship using a string

An Example
----------

[](#an-example)

This example shows how your model, repository and controller could be set up.

*app\\Models\\Post.php*

```
    namespace App\Models;

    class Post extends Illuminate\Database\Eloquent\Model
    {
        public function comments()
        {
            return $this->hasMany('App\Models\Comment');
        }

        public function author()
        {
            return $this->hasOne('App\Models\User');
        }
    }

```

*app\\Repositories\\PostRepository.php*

```
    namespace App\Repositories;

    use Weeks\Laravel\Repositories\BaseEloquentRepository;

    class PostRepository extends BaseEloquentRepository
    {
        protected $model = App\Models\Post::class;
        protected $relationships = ['comments', 'author'];
    }
```

*app\\Http\\Controllers\\PostController.php*

```
    namespace App\Http\Controllers;

    use App\Repositories\PostRepository;

    class PostController extends Controller
    {
        protected $posts;

        public function __construct(PostRepository $posts)
        {
            $this->posts = $posts;
        }

        public function show($id)
        {
            // get the post and eagerly load the comments for it too.
            $post = $this->posts->with('comments')->getById($id);

            return view('posts.show', compact('post'));
        }
    }
```

HTTP Exceptions
---------------

[](#http-exceptions)

To enable http exceptions (like Eloquent's findOrFail method) on a repository just have it `use \Weeks\Laravel\Repositories\Traits\ThrowsHttpExceptions;`.

If the below methods return null they will throw a 404 error instead of returning null.

```
getById
getItemByColumn

```

An example using the ThrowsHttpExceptions trait.

```
    namespace App\Repositories;

    use Weeks\Laravel\Repositories\BaseEloquentRepository;
    use Weeks\Laravel\Repositories\Traits\ThrowsHttpExceptions;

    class PostRepository extends BaseEloquentRepository
    {
        use ThrowsHttpExceptions;

        protected $model = App\Models\Post::class;
    }
```

You can temporarily disable HTTP exceptions by chaining `disableHttpExceptions()` before performing a query. For example:

```
$posts = new PostRepository();

$post = $posts->disableHttpExceptions()->getById(1000); // returns null rather than throwing a 404 error.
```

Caching
-------

[](#caching)

To enable caching on a repository just have it `use \Weeks\Laravel\Repositories\Traits\CacheResults;`.

By doing this all the repository ['read'](https://en.wikipedia.org/wiki/Create,_read,_update_and_delete) methods cache their results using Laravel's caching system.

```
// Methods that cache when using the CacheResults trait.
getAll
getPaginated
getForSelect
getById
getItemByColumn
getCollectionByColumn
getActively

```

An example using the CacheResults trait.

```
    namespace App\Repositories;

    use Weeks\Laravel\Repositories\BaseEloquentRepository;
    use Weeks\Laravel\Repositories\Traits\CacheResults;

    class PostRepository extends BaseEloquentRepository
    {
        use CacheResults;

        protected $model = App\Models\Post::class;
        protected $relationships = ['comments', 'author'];
        protected $nonCacheableMethods = ['getById'];
        protected $cacheTtl = 30;
    }
```

You can force the result of a request not to be cached by adding the method name to the `$nonCacheableMethods` property of your repository. See example above.

By default the [ttl](https://en.wikipedia.org/wiki/Time_to_live) of a cache item is 60 minutes. This can be overwritten by updating the ` $cacheTtl` property of your repository. See example above.

Caching can be disabled programatically by calling `disabledCaching()` on your repository. This method returns the repository to enable method chaining e.g. `$repo->disableCaching()->getAll();`.

###  Health Score

34

—

LowBetter than 77% of packages

Maintenance18

Infrequent updates — may be unmaintained

Popularity27

Limited adoption so far

Community13

Small or concentrated contributor base

Maturity64

Established project with proven stability

 Bus Factor1

Top contributor holds 97.1% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~133 days

Total

2

Last Release

3726d ago

Major Versions

v0.1 → v1.02016-03-05

### Community

Maintainers

![](https://www.gravatar.com/avatar/c09e84a218791021e234bd67e0a03ed0183747a46e2930c60358c576a707b6d8?d=identicon)[dannyweeks](/maintainers/dannyweeks)

---

Top Contributors

[![dannyweeks](https://avatars.githubusercontent.com/u/4365775?v=4)](https://github.com/dannyweeks "dannyweeks (33 commits)")[![kirkaracha](https://avatars.githubusercontent.com/u/3633070?v=4)](https://github.com/kirkaracha "kirkaracha (1 commits)")

---

Tags

laraveleloquentlaravel 5repositoryrepositories

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/dannyweeks-laravel-base-repository/health.svg)

```
[![Health](https://phpackages.com/badges/dannyweeks-laravel-base-repository/health.svg)](https://phpackages.com/packages/dannyweeks-laravel-base-repository)
```

###  Alternatives

[torann/laravel-repository

Base repository implementation for Laravel

88497.8k2](/packages/torann-laravel-repository)[czim/laravel-repository

Repository for Laravel (inspired by and indebted to Bosnadev/Repositories)

54110.0k4](/packages/czim-laravel-repository)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
