1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Larrock\Core\Traits; |
4
|
|
|
|
5
|
|
|
use Session; |
6
|
|
|
use Redirect; |
7
|
|
|
use Validator; |
8
|
|
|
use Larrock\Core\Component; |
9
|
|
|
use Illuminate\Http\Request; |
10
|
|
|
use Larrock\Core\Helpers\MessageLarrock; |
11
|
|
|
use Larrock\Core\Events\ComponentItemStored; |
12
|
|
|
use Larrock\Core\Helpers\FormBuilder\FormDate; |
13
|
|
|
|
14
|
|
|
trait AdminMethodsStore |
15
|
|
|
{ |
16
|
|
|
/** @var Component */ |
17
|
|
|
protected $config; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* @var bool Разрешать ли делать редиректы |
21
|
|
|
* Возвращать пользователя на страницу вместо ответа api |
22
|
|
|
*/ |
23
|
|
|
public $allow_redirect = true; |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* @param Component $config |
27
|
|
|
* @return bool |
28
|
|
|
*/ |
29
|
|
|
public function setConfig($config) |
30
|
|
|
{ |
31
|
|
|
$this->config = $config; |
32
|
|
|
|
33
|
|
|
return true; |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
/** |
37
|
|
|
* Store a newly created resource in storage. |
38
|
|
|
* |
39
|
|
|
* @param \Illuminate\Http\Request $request |
40
|
|
|
* @return \Illuminate\Database\Eloquent\Model|\Illuminate\Http\RedirectResponse|\Illuminate\Http\Response |
41
|
|
|
* @throws \Exception |
42
|
|
|
*/ |
43
|
|
|
public function store(Request $request) |
44
|
|
|
{ |
45
|
|
|
$data = $this->config->getModel(); |
46
|
|
|
$data->fill($request->all()); |
47
|
|
|
|
48
|
|
|
foreach ($this->config->rows as $row) { |
49
|
|
|
if ($row->fillable && ! isset($data->{$row->name})) { |
50
|
|
|
if ($row instanceof FormDate) { |
51
|
|
|
$data->{$row->name} = $request->input('date', date('Y-m-d')); |
52
|
|
|
} else { |
53
|
|
|
$data->{$row->name} = $request->input($row->name, $row->default); |
54
|
|
|
} |
55
|
|
|
} |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
$validator = Validator::make($data->toArray(), $this->config->getValid()); |
59
|
|
|
if ($validator->fails()) { |
60
|
|
|
if ($this->allow_redirect) { |
61
|
|
|
if (array_key_exists('url', $validator->failed())) { |
62
|
|
|
$search = $this->config->getModel()::whereUrl($data->url)->first(); |
63
|
|
|
MessageLarrock::danger('Материал с тарим url уже существует: /admin/'.$this->config->name.'/'.$search->id.'/edit'); |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
return back()->withInput($request->except('password'))->withErrors($validator); |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
return response()->json(['status' => 'danger', 'message' => $validator->errors()->first()]); |
|
|
|
|
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
$data->save(); |
73
|
|
|
event(new ComponentItemStored($this->config, $data, $request)); |
74
|
|
|
\Cache::flush(); |
75
|
|
|
Session::push('message.success', 'Материал '.$request->input('title').' добавлен'); |
76
|
|
|
if ($this->allow_redirect) { |
77
|
|
|
return Redirect::to('/admin/'.$this->config->name.'/'.$data->id.'/edit')->withInput(); |
78
|
|
|
} |
79
|
|
|
|
80
|
|
|
return $data; |
81
|
|
|
} |
82
|
|
|
} |
83
|
|
|
|