BaseRepository
Overview
The BaseRepository class is an abstract repository layer class designed to provide a standardized set of data access operations for Eloquent models. It encapsulates database interactions and provides methods for CRUD operations, filtering, searching, and data import/export.
This class is intended to be extended by concrete repository classes for specific models. It relies on a model class ( specified by $modelClass) to perform actual data operations.
Properties
- protected string $modelClass: The class name of the Eloquent model to use (defaults to
Model::class). - private static $instance: Singleton instance of the repository.
- protected Model $model: The Eloquent model instance.
- private array $modelTableColumns: Array of fillable columns from the model.
- private array $filterKeys: Array of filter keys defined in the model.
- private array $relationSearchableKeys: Array of searchable keys for related models.
- private array $searchableKeys: Array of searchable keys for the model.
- private string $tableName: The table name associated with the model.
Constructor
- public function __construct()
- Instantiates the model using the class specified in
$modelClass. - Initializes
$tableName,$searchableKeys,$relationSearchableKeys, and$filterKeysbased on model methods. - Populates
$modelTableColumnswith fillable columns.
- Instantiates the model using the class specified in
Methods
make
public static function make(): staticReturns a singleton instance of the repository.
- Returns: The singleton instance of the repository.
getTableColumns
public function getTableColumns(): arrayRetrieves the fillable columns of the model.
- Returns: Array of fillable columns.
all
public function all(array $relationships = []): Collection|array|RegularCollectionRetrieves all records, optionally eager loading relationships.
- Parameters:
$relationships: Array of relationship names to eager load.
- Returns:
Collection,array, orRegularCollectionof models.
globalQuery
public function globalQuery(array $relations = []): BuilderBuilds a query with filters, search, and ordering applied.
- Parameters:
$relations: Array of relationship names to eager load.
- Returns: Eloquent
Builderinstance.
allWithPagination
public function allWithPagination(array $relationships = [], int $per_page = 10): LengthAwarePaginatorRetrieves records with pagination.
- Parameters:
$relationships: Array of relationship names to eager load.$per_page: Number of records per page (default: 10).
- Returns:
LengthAwarePaginatorof models.
create
public function create(array $data, array $relationships = []): ModelCreates a new record.
- Parameters:
$data: Array of attributes for the new record.$relationships: Array of related data to associate.
- Returns: The created
Modelinstance.
delete
public function delete(string|int|Model $id): ?boolDeletes a record by its ID.
- Parameters:
$id: The primary key or model instance to delete.
- Returns:
bool|null—trueif deleted,falseif not, ornullif not found.
find
public function find($id, array $relationships = []): ?ModelRetrieves a single record by ID, optionally eager loading relationships.
- Parameters:
$id: The primary key of the record to retrieve.$relationships: Array of relationship names to eager load.
- Returns: The
Modelinstance ornullif not found.
update
public function update(array $data, string|int|Model $id, array $relationships = []): ?ModelUpdates an existing record by ID.
- Parameters:
$data: Array of attributes to update.$id: The primary key or model instance to update.$relationships: Array of related data to update.
- Returns: The updated
Modelinstance ornullif not found.
export
public function export(array $ids = []): BinaryFileResponseExports records (optionally filtered by IDs) to a file (e.g., Excel or CSV).
- Parameters:
$ids: Array of record IDs to export (optional).
- Returns:
BinaryFileResponsefor file download. - Throws:
Exceptionon failure.
getImportExample
public function getImportExample(): BinaryFileResponseProvides an example file for data import (e.g., Excel template).
- Returns:
BinaryFileResponsefor file download. - Throws:
Exception,\PhpOffice\PhpSpreadsheet\Writer\Exceptionon failure.
import
public function import(): voidImports data from a file (implementation in repository).
- Returns:
void
Filtering, Searching, and Ordering
Filtering
The BaseRepository class supports filtering records based on predefined filter keys. These keys are defined in the model using the filterArray method. The globalQuery method applies these filters to the query.
How Filtering Works
- Filter Keys: Defined in the model using the
filterArraymethod. Each filter key can specify a field, operator, relation, method, and callback. - Applying Filters: The
filterFieldsmethod iterates over the filter keys and applies them to the query based on the request parameters.
Example
// In your model
public function filterArray(): array
{
return [
['field' => 'status', 'operator' => '='],
['field' => 'created_at', 'operator' => '>=', 'method' => 'whereDate'],
];
}Searching
The BaseRepository class supports searching records based on predefined searchable keys. These keys are defined in the model using the searchableArray and relationsSearchableArray methods.
How Searching Works
- Searchable Keys: Defined in the model using the
searchableArraymethod for direct attributes andrelationsSearchableArrayfor related attributes. - Applying Search: The
addSearchmethod checks for asearchparameter in the request and applies the search conditions to the query.
Example
// In your model
public function searchableArray(): array
{
return ['name', 'email'];
}
public function relationsSearchableArray(): array
{
return [
'profile' => ['bio'],
];
}Ordering
The BaseRepository class supports ordering records based on request parameters. The orderQueryBy method applies the ordering to the query.
How Ordering Works
- Sort Columns: The
sort_colparameter in the request specifies the column to sort by, andsort_dirspecifies the direction (asc or desc). - Applying Ordering: The
orderQueryBymethod checks for thesort_colparameter and applies the ordering to the query.
Example
// Request parameters
?sort_col=name&sort_dir=ascUsage Example
To use BaseRepository, extend it in your own repository class and specify the model class:
use App\Repositories\Contracts\BaseRepository;
use App\Models\User;
/**
* @extends BaseRepository<User>
*/
class UserRepository extends BaseRepository
{
protected string $modelClass = User::class;
// Add custom data access logic here
}Notes
- This class is abstract and should not be instantiated directly.
- All data operations are delegated to the model specified by
$modelClass. - Extend this class to implement model-specific data access logic in your application.
