回答編集履歴
2
リンクがおかしかったので修正しました。
answer
CHANGED
@@ -49,4 +49,4 @@
|
|
49
49
|
}
|
50
50
|
```
|
51
51
|
|
52
|
-
参考: [updateOrCreate](https://readouble.com/laravel/6.x/ja/eloquent.html#other-creation-methods
|
52
|
+
参考: [updateOrCreate](https://readouble.com/laravel/6.x/ja/eloquent.html#other-creation-methods)
|
1
変更案を追記しました。
answer
CHANGED
@@ -1,3 +1,52 @@
|
|
1
1
|
updateメソッドの `$goods = Goods::find($id);`(74行目)で取得できず、$goodsがnullになっているのだと思います。
|
2
2
|
|
3
|
-
$idにはEmployeeのidの値が渡ってきているので、その$idでGoodsを取得することはできません。
|
3
|
+
$idにはEmployeeのidの値が渡ってきているので、その$idでGoodsを取得することはできません。
|
4
|
+
|
5
|
+
(追記)
|
6
|
+
|
7
|
+
例えば、以下のような感じにするとどうでしょうか。
|
8
|
+
フォームから `goods[0][uniform]` のような name で送信させると、
|
9
|
+
アクションでは `$request->goods` で配列として受け取れるはずですので、その配列を処理すれば良さそうです。
|
10
|
+
|
11
|
+
employee_edit.blade.php
|
12
|
+
|
13
|
+
```blade
|
14
|
+
@foreach($employee->goods as $i => $goods)
|
15
|
+
<input type="hidden" name="goods[{{ $i }}][id]" value="{{ $goods->id }}">
|
16
|
+
...
|
17
|
+
<select name="goods[{{ $i }}][uniform]" ... > ... </select>
|
18
|
+
...
|
19
|
+
<select name="goods[{{ $i }}][winter_clothes]" ... > ... </select>
|
20
|
+
...
|
21
|
+
<select name="goods[{{ $i }}][shoes]" ... > ... </select>
|
22
|
+
...
|
23
|
+
<input type="text" name="goods[{{ $i }}][other]" ... >
|
24
|
+
...
|
25
|
+
<input type="text" name="goods[{{ $i }}][memo]" ... >
|
26
|
+
...
|
27
|
+
@endforeach
|
28
|
+
```
|
29
|
+
|
30
|
+
EmployeesController.php
|
31
|
+
|
32
|
+
```php
|
33
|
+
public function update(Request $request, $id)
|
34
|
+
{
|
35
|
+
// Employeeの更新
|
36
|
+
$employee = Employee::find($id);
|
37
|
+
$employee->office = $request->office;
|
38
|
+
$employee->save();
|
39
|
+
|
40
|
+
// Goodsの更新
|
41
|
+
foreach ($request->goods as $goods) {
|
42
|
+
$employee->goods()->updateOrCreate([
|
43
|
+
'id' => $goods['id'],
|
44
|
+
], $goods);
|
45
|
+
}
|
46
|
+
|
47
|
+
// 更新後はリダイレクト
|
48
|
+
return redirect()->route( ... );
|
49
|
+
}
|
50
|
+
```
|
51
|
+
|
52
|
+
参考: [updateOrCreate](https://readouble.com/laravel/6.x/ja/eloquent.html#other-creation-methods#other-creation-methods)
|