/
BaseRepository.php
executable file
·106 lines (94 loc) · 2.02 KB
/
BaseRepository.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
<?php
/**
* @author dungnt13
* @date 8/18/2015
*/
namespace App\Funny\Repositories;
abstract class BaseRepository
{
/**
* The model instance
*
* @var \Illuminate\Database\Eloquent\Model
*/
protected $model;
/**
* Get a new instance of the model
*
* @param array $attributes
* @return \Illuminate\Database\Eloquent\Model
*/
public function getNew(array $attributes = array())
{
return $this->model->newInstance($attributes);
}
/**
* Get Model by id.
*
* @param int $id
* @return \App\Models\Model
*/
public function findById($id)
{
return $this->model->findOrFail($id);
}
/**
* Destroy a model
*
* @param int $id
*/
public function destroy($id)
{
$this->findById($id)->delete();
}
/**
* Restore a model
*
* @param int $id
*/
public function restored($id)
{
$object = $this->model->withTrashed()->find($id);
$object->restore();
}
/**
* Save model to database
*
* @param $array
* @return static
*/
public function create($array)
{
$model = $this->getNew();
foreach ($array as $key => $value) {
if ($key != 'id') {
$model->{$key} = $value;
}
}
$model->save();
return $model;
}
/**
* update model to database
*
* @param $array
* @param int $id
* @return \App\Models\Model
*/
public function update($array, $id = 0)
{
$id = $id != 0 ? $id : $array['id'];
$model = $this->findById($id);
foreach ($array as $key => $value) {
if ($key != 'id' && $key != '_token') {
$model->{$key} = $value;
}
}
$model->save();
return $model;
}
public function findAll($orderColumn = 'create_at', $orderDir = 'desc')
{
return $this->model->orderBy($orderColumn, $orderDir)->get();
}
}