Completed
Push — master ( 5e8e24...d52d7e )
by Alexandr
01:40
created

AdminMethodsUpdate::update()   B

Complexity

Conditions 6
Paths 8

Size

Total Lines 27
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 1
Metric Value
c 1
b 1
f 1
dl 0
loc 27
rs 8.439
cc 6
eloc 17
nc 8
nop 2
1
<?php
2
3
namespace Larrock\Core\Traits;
4
5
use Validator;
6
use Larrock\Core\Component;
7
use Illuminate\Http\Request;
8
use Larrock\Core\Helpers\MessageLarrock;
9
use Larrock\Core\Events\ComponentItemUpdated;
10
use Larrock\Core\Helpers\FormBuilder\FormDate;
11
12
trait AdminMethodsUpdate
13
{
14
    /**
15
     * @var Component
16
     */
17
    protected $config;
18
19
    /**
20
     * Update the specified resource in storage.
21
     *
22
     * @param  \Illuminate\Http\Request $request
23
     * @param  int $id
24
     * @return \Illuminate\Http\RedirectResponse
25
     * @throws \Exception
26
     */
27
    public function update(Request $request, $id)
28
    {
29
        $data = $this->config->getModel()::find($id);
30
        $data->fill($request->all());
31
32
        foreach ($this->config->rows as $row) {
33
            if (\in_array($row->name, $data->getFillable(), false) && ! isset($data->{$row->name})) {
34
                if ($row instanceof FormDate) {
35
                    $data->{$row->name} = $request->input('date', date('Y-m-d'));
36
                } else {
37
                    $data->{$row->name} = $request->input($row->name, $row->default);
38
                }
39
            }
40
        }
41
42
        $validator = Validator::make($data->toArray(), $this->config->getValid($id));
43
        if ($validator->fails()) {
44
            return back()->withInput($request->except('password'))->withErrors($validator);
45
        }
46
47
        $data->save();
48
        event(new ComponentItemUpdated($this->config, $data, $request));
49
        MessageLarrock::success('Материал '.$request->input('title').' изменен');
50
        \Cache::flush();
51
52
        return back();
53
    }
54
}
55