|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace WebDevEtc\BlogEtc\Repositories; |
|
4
|
|
|
|
|
5
|
|
|
use Illuminate\Contracts\Pagination\LengthAwarePaginator; |
|
6
|
|
|
use Illuminate\Database\Eloquent\Builder; |
|
7
|
|
|
use Illuminate\Database\Eloquent\ModelNotFoundException; |
|
8
|
|
|
use WebDevEtc\BlogEtc\Exceptions\CategoryNotFoundException; |
|
9
|
|
|
use WebDevEtc\BlogEtc\Models\Category; |
|
10
|
|
|
|
|
11
|
|
|
class CategoriesRepository |
|
12
|
|
|
{ |
|
13
|
|
|
/** @var Category */ |
|
14
|
|
|
private $model; |
|
15
|
|
|
|
|
16
|
|
|
/** |
|
17
|
|
|
* BlogEtcCategoriesRepository constructor. |
|
18
|
|
|
*/ |
|
19
|
|
|
public function __construct(Category $model) |
|
20
|
|
|
{ |
|
21
|
|
|
$this->model = $model; |
|
22
|
|
|
} |
|
23
|
|
|
|
|
24
|
|
|
/** |
|
25
|
|
|
* Return all blog etc categories, ordered by category_name, paginated. |
|
26
|
|
|
*/ |
|
27
|
|
|
public function indexPaginated(int $perPage = 25): LengthAwarePaginator |
|
28
|
|
|
{ |
|
29
|
|
|
return $this->query() |
|
30
|
|
|
->orderBy('category_name') |
|
31
|
|
|
->paginate($perPage); |
|
32
|
|
|
} |
|
33
|
|
|
|
|
34
|
|
|
/** |
|
35
|
|
|
* Return new instance of the Query Builder for this model. |
|
36
|
|
|
*/ |
|
37
|
|
|
public function query(): Builder |
|
38
|
|
|
{ |
|
39
|
|
|
return $this->model->newQuery(); |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
|
|
/** |
|
43
|
|
|
* Find and return a blog etc category. |
|
44
|
|
|
*/ |
|
45
|
|
|
public function find(int $categoryID): Category |
|
46
|
|
|
{ |
|
47
|
|
|
try { |
|
48
|
|
|
return $this->query()->findOrFail($categoryID); |
|
49
|
|
|
} catch (ModelNotFoundException $e) { |
|
50
|
|
|
throw new CategoryNotFoundException('Unable to find a blog category with ID: '.$categoryID); |
|
51
|
|
|
} |
|
52
|
|
|
} |
|
53
|
|
|
|
|
54
|
|
|
/** |
|
55
|
|
|
* Find and return a blog etc category, based on its slug. |
|
56
|
|
|
*/ |
|
57
|
|
|
public function findBySlug(string $categorySlug): Category |
|
58
|
|
|
{ |
|
59
|
|
|
try { |
|
60
|
|
|
return $this->query()->where('slug', $categorySlug)->firstOrFail(); |
|
61
|
|
|
} catch (ModelNotFoundException $e) { |
|
62
|
|
|
throw new CategoryNotFoundException('Unable to find a blog category with slug: '.$categorySlug); |
|
63
|
|
|
} |
|
64
|
|
|
} |
|
65
|
|
|
} |
|
66
|
|
|
|