1 | <?php |
||
2 | |||
3 | namespace Mikehins\Translatable; |
||
4 | |||
5 | use Illuminate\Database\Eloquent\Model; |
||
6 | use Illuminate\Database\Query\Builder; |
||
7 | |||
8 | class Translation extends Model |
||
9 | { |
||
10 | protected $table = 'translations'; |
||
11 | |||
12 | protected $primaryKey = 'translatable_id'; |
||
13 | |||
14 | protected $guarded = []; |
||
15 | |||
16 | public static function getTableName() |
||
17 | { |
||
18 | return (new static)->getTable(); |
||
19 | } |
||
20 | |||
21 | public function store(array $attributes, array $values = []): int |
||
0 ignored issues
–
show
|
|||
22 | { |
||
23 | $this->deleteTranslation($attributes['translatable_type'], $attributes['translatable_id']); |
||
24 | |||
25 | collect($attributes['translatable'])->each(function ($data, $locale) use ($attributes) { |
||
26 | collect($data)->each(function ($value, $key) use ($attributes, $locale) { |
||
27 | self::insert([ |
||
28 | 'key' => $key, |
||
29 | 'value' => $value ?? '', |
||
30 | 'locale' => $locale, |
||
31 | 'translatable_type' => $attributes['translatable_type'], |
||
32 | 'translatable_id' => $attributes['translatable_id'], |
||
33 | ]); |
||
34 | }); |
||
35 | }); |
||
36 | |||
37 | return $attributes['translatable_id']; |
||
38 | } |
||
39 | |||
40 | public function deleteTranslation($type, $id) |
||
41 | { |
||
42 | $instance = self::where([ |
||
43 | 'translatable_type' => $type, |
||
44 | 'translatable_id' => $id, |
||
45 | ]); |
||
46 | |||
47 | if ($instance) { |
||
48 | $instance->delete(); |
||
49 | } |
||
50 | } |
||
51 | |||
52 | /** |
||
53 | * @param QueryBuilder $query |
||
54 | * @param string $key |
||
55 | * @param string $order |
||
56 | * @return Builder |
||
57 | */ |
||
58 | public function scopeOrderTranslationByKey($query, $key = 'name', $order = 'asc') |
||
59 | { |
||
60 | return $query->select(\DB::raw(' |
||
61 | IF(translations.`key` = "' . $key . '", translations.value, "") as ' . $key . ' |
||
62 | '))->where( |
||
63 | 'translations.locale', |
||
64 | '=', |
||
65 | app()->getLocale() |
||
66 | )->orderBy( |
||
67 | \DB::raw($key . ' ' . $order) |
||
68 | )->groupBy('translations.translatable_id'); |
||
69 | } |
||
70 | |||
71 | public function translatable() |
||
72 | { |
||
73 | return $this->morphTo(); |
||
74 | } |
||
75 | |||
76 | public function getTranslatableAttribute() |
||
77 | { |
||
78 | return $this->attributes['translatable'] = request('translatable'); |
||
79 | } |
||
80 | } |
||
81 |
This check looks for parameters that have been defined for a function or method, but which are not used in the method body.