smashed-egg/laravel-model-repository

Add support for Model Repositories to Laravel

0.3.0 2023-09-27 09:29 UTC

This package is auto-updated.

Last update: 2024-04-18 14:44:33 UTC


README

main.jpg

Laravel Model Repository

Latest Stable Version Downloads this Month

This package provides a Repository class for people who like SOLID principles (Separation of concerns and all that jazz) and want their repository logic in a different class.

Requirements

  • PHP 8.0.2+
  • Laravel 9.0+

Installation

To install this package please run:

composer require smashed-egg/laravel-model-repository

You can publish a configuration file that comes with the package:

php artisan vendor:publish --provider="SmashedEgg\LaravelModelRepository\ServiceProvider"

Support Me

Do you like this package? Does it improve you're development. Consider sponsoring to help with future development.

Buy me a coffee!

Thank you!

Usage

Configuration (optional)

If you have published the config file (located at config/smashed_egg/model_repository.php) you can override the base repository class used with the make command, as well as a model to repository mapping, which is useful when using the RepositoryManager class (more on that later).

<?php

return [

    /**
     * The base Repository Class to use for all Repositories generated via cli
     */
    'base_repository' => \SmashedEgg\LaravelModelRepository\Repository\Repository::class,

    /**
     * Map of Models to Repository classes
     *
     * Useful when using the RepositoryManager class
     */
    'model_repository_map' => [
        //\App\Models\User::class => \App\Repositories\UserRepository::class,
    ],
];

Creating a Model Repository

You can run the following command to create a new Repository for your Model, assuming you already have a User model:

php artisan smashed-egg:make:repository UserRepository

or using the command alias:

php artisan se:make:repository UserRepository

You can even override the base repository class

php artisan se:make:repository UserRepository --base-repository="App\Repositories\CustomRepository"

Out of the box you get access to the following methods, that will pass along to the Model instance:

  • save(Model $model)
  • delete(Model $model, bool $force = false) - When using the SoftDeletes trait you can control whether you want to soft or hard delete
  • restore(Model $model) - When using the SoftDeletes trait you can undo a soft deletion
  • query - Start an eloquent query
  • baseQuery - Start a database query

Using the RepositoryManager

If you have configured a model to repository mapping