1 | <?php |
||
8 | class UserDevice extends Model |
||
9 | { |
||
10 | use SoftDeletes; |
||
11 | |||
12 | /** |
||
13 | * The attributes that should be mutated to dates. |
||
14 | * |
||
15 | * @var array |
||
16 | */ |
||
17 | protected $dates = ['deleted_at']; |
||
18 | |||
19 | /** |
||
20 | * The attributes that are mass assignable. |
||
21 | * |
||
22 | * @var array |
||
23 | */ |
||
24 | protected $fillable = ['user_id', 'device_id']; |
||
25 | |||
26 | /** |
||
27 | * Touch UserDevice model. |
||
28 | * |
||
29 | * @param int $user_id |
||
30 | * @param int $device_id |
||
31 | * @return static|null |
||
32 | */ |
||
33 | public static function touchUserDevice($user_id, $device_id) |
||
34 | { |
||
35 | if ($user_id && $device_id) { |
||
36 | $instance = static::withTrashed() |
||
37 | ->firstOrNew(compact('user_id', 'device_id')); |
||
38 | |||
39 | if ($instance->trashed()) { |
||
40 | $instance->restore(); |
||
41 | } |
||
42 | |||
43 | $instance->touch(); |
||
44 | |||
45 | return $instance; |
||
46 | } |
||
47 | } |
||
48 | |||
49 | /** |
||
50 | * Fetch records. |
||
51 | * |
||
52 | * @param int|null $userId |
||
53 | * @param int|null $deviceId |
||
54 | * @param bool $withTrashed |
||
55 | * @return mixed |
||
56 | */ |
||
57 | public static function findByUserDevice($userId = null, $deviceId = null, $withTrashed = false) |
||
58 | { |
||
59 | $query = static::query(); |
||
60 | |||
61 | if (! is_null($userId)) { |
||
62 | if (is_object($userId)) { |
||
63 | $userId = $userId->id; |
||
64 | } |
||
65 | $query->where('user_id', $userId); |
||
66 | } |
||
67 | |||
68 | if (! is_null($deviceId)) { |
||
69 | if (is_object($deviceId)) { |
||
70 | $deviceId = $deviceId->id; |
||
71 | } |
||
72 | $query->where('device_id', $deviceId); |
||
73 | } |
||
74 | |||
75 | if ($withTrashed) { |
||
76 | $query->withTrashed(); |
||
77 | } |
||
78 | |||
79 | if (! is_null($userId) && ! is_null($deviceId)) { |
||
80 | return $query->first(); |
||
81 | } |
||
82 | |||
83 | return $query->orderBy('updated_at', 'desc')->get(); |
||
84 | } |
||
85 | |||
86 | /** |
||
87 | * Delete model. |
||
88 | * |
||
89 | * @param int $userId |
||
90 | * @param init $deviceId |
||
91 | * @return bool|null |
||
92 | */ |
||
93 | public static function deleteUserDevice($userId, $deviceId) |
||
94 | { |
||
95 | if ($userId && |
||
96 | $deviceId && |
||
97 | $instance = static::findByUserDevice($userId, $deviceId)) { |
||
98 | $instance->delete(); |
||
99 | } |
||
100 | } |
||
101 | } |
||
102 |