1
1

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 1 year has passed since last update.

【Laravel】get() / first() / find()の返り値の違い

Last updated at Posted at 2022-03-25

環境

Laravel v9.5.1 (PHP v8.1.3)

状況

deleteする際エラーが発生。

Method delete does not exist.
public function destory($id)
{
	$article = Article::where('id', $id)->get();
	$article->delete();

	return redirect()->route('home');
}

原因

Article::where('id', $id)->get();の返り値がCollectionクラスだから。
Collectionクラスに対してdeleteできないというエラーだった。

(Collectionクラスは、RailsでいうEnumerableモジュールだと思う)

>>> Article::where('id', 9)->get();
=> Illuminate\Database\Eloquent\Collection {#4467
     all: [
       App\Models\Article {#4461
         id: 9,
         user_id: 1,
         title: "title",
         content: "content",
         created_at: null,
         updated_at: null,
       },
     ],
   }

解決法

public function destory($id)
{
    $article = Article::where('id', $id)->first();
    //OR
	$article = Article::find($id);
	$article->delete();

	return redirect()->route('home');
}

get / first / findの返り値の違い

get() → Eloquent Collectionクラス
first() → modelオブジェクト
find() → modelオブジェクト

Eloquent Collectionクラス:Illuminate\Database\Eloquent\Collectionのインスタンス

>>> Article::where('id', 9)->first();
=> App\Models\Article {#4460
     id: 9,
     user_id: 1,
     title: "title",
     content: "content",
     created_at: null,
     updated_at: null,
   }

>>> Article::find(9);
=> App\Models\Article {#4477
     id: 9,
     user_id: 1,
     title: "title",
     content: "content",
     created_at: null,
     updated_at: null,
   }

最適解

ただ、deleteする際の取得の仕方としてよりベターなのはfindOrFailを使う。
findOrFailで取得したいarticleが見つからなかったときはエラーを吐いてくれる。

(Railsでは、@article.find(id)だけでエラー吐いてくれる)

public function destory($id)
{
	$article = Article::findOrFail($id);
	$article->delete();

	return redirect()->route('home');
}

参考

1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?