1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Longman\LaravelMultiLang; |
4
|
|
|
|
5
|
|
|
use Illuminate\Http\Request; |
6
|
|
|
use Longman\LaravelMultiLang\Models\Text; |
7
|
|
|
|
8
|
|
|
trait TextsTrait |
9
|
|
|
{ |
10
|
|
|
|
11
|
|
|
public function index(Request $request) |
12
|
|
|
{ |
13
|
|
|
$options['lang'] = config('multilang.default_locale'); |
|
|
|
|
14
|
|
|
|
15
|
|
|
if ($request->lang) { |
16
|
|
|
$options['lang'] = $request->lang; |
|
|
|
|
17
|
|
|
} |
18
|
|
|
|
19
|
|
|
if ($request->keyword) { |
20
|
|
|
$options['keyword'] = $request->keyword; |
|
|
|
|
21
|
|
|
} |
22
|
|
|
|
23
|
|
|
if ($request->scope) { |
24
|
|
|
$options['scope'] = $request->scope; |
|
|
|
|
25
|
|
|
} |
26
|
|
|
|
27
|
|
|
$texts = Text::where(function ($q) use ($options) { |
28
|
|
|
foreach ($options as $k => $v) { |
29
|
|
|
if ($k == 'keyword') { |
30
|
|
|
$q->where(function ($query) use ($v) { |
31
|
|
|
$query->where('key', 'LIKE', '%' . $v . '%')->orWhere('value', 'LIKE', '%' . $v . '%'); |
32
|
|
|
}); |
33
|
|
|
} else { |
34
|
|
|
$q->where($k, $v); |
35
|
|
|
} |
36
|
|
|
} |
37
|
|
|
})->orderBy('value', 'asc')->get(); |
38
|
|
|
|
39
|
|
|
if (isset($request->search)) { |
40
|
|
|
$options['search'] = true; |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
$options['keyword'] = $request->keyword; |
44
|
|
|
|
45
|
|
|
$data['texts'] = $texts; |
|
|
|
|
46
|
|
|
$data['options'] = $options; |
47
|
|
|
|
48
|
|
|
return view($this->view, $data); |
|
|
|
|
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
public function save(Request $request) |
52
|
|
|
{ |
53
|
|
|
$this->validate($request, [ |
|
|
|
|
54
|
|
|
'texts' => 'required|array', |
55
|
|
|
]); |
56
|
|
|
|
57
|
|
|
$locales = array_keys(config('multilang.locales')); |
58
|
|
|
foreach ($request->texts as $lang => $items) { |
59
|
|
|
if (!in_array($lang, $locales)) { |
60
|
|
|
//to do must set errors |
61
|
|
|
continue; |
62
|
|
|
} |
63
|
|
|
foreach ($items as $key => $value) { |
64
|
|
|
Text::where('lang', $lang) |
65
|
|
|
->where('key', $key) |
66
|
|
|
->update(['value' => $value]); |
67
|
|
|
} |
68
|
|
|
} |
69
|
|
|
return redirect()->back(); |
70
|
|
|
} |
71
|
|
|
} |
72
|
|
|
|
Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.
Let’s take a look at an example:
As you can see in this example, the array
$myArray
is initialized the first time when the foreach loop is entered. You can also see that the value of thebar
key is only written conditionally; thus, its value might result from a previous iteration.This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.