73 lines
1.6 KiB
PHP
73 lines
1.6 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Repositories;
|
|
|
|
use Illuminate\Database\Eloquent\Model;
|
|
use Illuminate\Support\Collection;
|
|
|
|
/**
|
|
* Base repository implementation using Eloquent models.
|
|
*/
|
|
class BaseRepository implements BaseRepositoryInterface
|
|
{
|
|
public function __construct(protected Model $model)
|
|
{
|
|
}
|
|
|
|
/**
|
|
* @param array<int, string> $columns
|
|
* @return Collection<int, Model>
|
|
*/
|
|
public function all(array $columns = ['*']): Collection
|
|
{
|
|
return $this->model->newQuery()->get($columns);
|
|
}
|
|
|
|
/**
|
|
* @param int|string $id
|
|
* @param array<int, string> $columns
|
|
*/
|
|
public function find(int|string $id, array $columns = ['*']): ?Model
|
|
{
|
|
return $this->model->newQuery()->find($id, $columns);
|
|
}
|
|
|
|
/**
|
|
* @param array<string, mixed> $attributes
|
|
*/
|
|
public function create(array $attributes): Model
|
|
{
|
|
// Uses mass assignment; ensure $fillable is set on the model
|
|
return $this->model->newQuery()->create($attributes);
|
|
}
|
|
|
|
/**
|
|
* @param int|string $id
|
|
* @param array<string, mixed> $attributes
|
|
*/
|
|
public function update(int|string $id, array $attributes): bool
|
|
{
|
|
$instance = $this->find($id);
|
|
if (! $instance) {
|
|
return false;
|
|
}
|
|
|
|
return $instance->fill($attributes)->save();
|
|
}
|
|
|
|
/**
|
|
* @param int|string $id
|
|
*/
|
|
public function delete(int|string $id): bool
|
|
{
|
|
$instance = $this->find($id);
|
|
if (! $instance) {
|
|
return false;
|
|
}
|
|
|
|
return (bool) $instance->delete();
|
|
}
|
|
}
|