manowartop / repository-service-laravel-pattern
Structure for the Laravel Service-Repository Pattern
v1.8
2023-08-11 13:53 UTC
Requires
- php: >=7.2
- illuminate/database: >=5.0
- illuminate/support: >=5.0
README
This package provides base repository and service for your Laravel Service-Repository pattern:
- Adds a repository layer, so you can avoid using your models directly and do all the calls via repository
- Adds a service layer which supports CRUD and search functionality
Usage
- Create model (f.e Post)
- Create a repository
PostRepository extends Manowartop\BaseRepositoryAndService\Repositories\BaseRepository
- Define property
protected $modelClass = Post::class;
in PostRepository - Create a service
PostService extends Manowartop\BaseRepositoryAndService\Services\BaseCrudService
- Define property in
protected $repository = PostRepository::class;
inPostService
That`s all. Now you have access to the next set of methods:
Repository methods
CRUD
getModel(): Model
- get the model of current repositorycreate(array $data): ?Model
- creates a new modelcreateMany(array $data): Illuminate\Support\Collection
- create many models from an arrayupdate($keyOrModel, array $data): ?Model
- update model by PK or model instanceupdateOrCreate(array $attributes, array $data): ?Model
- update or create modeldelete($keyOrModel): bool
- delete model by PK or instancedeleteMany(array $keysOrModels): void
- delete many (array of PK or models)
Query
find($key): ?Model
- find model by PKfindOrFail($value, ?string $column = null): Model
- find or fail by PKgetAll(array $search = []): Collection
- search a collection of modelsgetAllPaginated(array $search = [], int $pageSize = 15): LengthAwarePaginator
- search for paginated models collectionfindMany(array $attributes): Collection
- find all models by paramsfindFirst(array $attributes): ?Model
- find first model by paramswith(array $with): BaseRepositoryInterface
- set param$with
to specify relations to query models withwithCount(array $withCount): BaseRepositoryInterface
- set param$withCount
to specify relations_count to query models with
If you need to specify query filtering - just override protected function getFilteredQuery(array $search = []): Builder
in you repository
Service methods
getAllPaginated(array $search = [], int $pageSize = 15): LengthAwarePaginator
- search for paginated models collectiongetAll(array $search = []): Collection
- search a collection of modelsfindOrFail($value, ?string $column = null): Model
- find or fail by PKcreate(array $data): ?Model
- creates a new modelcreateMany(array $data): Illuminate\Support\Collection
- create many models from an arrayupdate($keyOrModel, array $data): ?Model
- update model by PK or model instanceupdateOrCreate(array $attributes, array $data): ?Model
- update or create modeldelete($keyOrModel): bool
- delete model by PK or instancedeleteMany(array $keysOrModels): void
- delete many (array of PK or models)