2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

laravel8 Method save does not exist. 解決メモ

Last updated at Posted at 2021-04-24
$user = User::where('id', $id)->get();
        $user->name = $name;
        $user->save();

この処理を行うと
Method save does not exist.
と出ました。

何が原因かというと、

get()はデフォルトでは結果が1件の場合でも「配列」を返します。
そのためget()をつかう場合はこのようにしないとエラーになってしまいます。

$users = User::where('id', $id)->get();
foreach($users as $user) {
$user->name= $name;
$user->save();
}

結果が1件だと分かりきっている場合はfirst()を使いましょう。

>```php
$user = User::where('id', $id)->first();
$user->name = $name;
$user->save();

もしくはこのようにupdate()メソッドを使っても良いかもしれません。

User::where('id', $id)->update(['name' => $name]);


配列に対してだとsaveメソットは正常に動作しない、とのことです。
[これ](https://teratail.com/questions/51127)の引用です。
2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?