0
0

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におけるRead(データ取得)処理

Last updated at Posted at 2023-08-17

Laravelで、モデルのデータを取得して画面に表示したいとき、いくつかのメソッドが用意されている。

ざっくりと、
1レコードを取得したいとき:first();
複数レコードを取得したいとき:get();で取得しforeachで出力する。
1件しかレコードがないテーブルのデータを取ってくるときも、どのメソッドで取ってくるかで、オブジェクトか配列か、データ形式が異なるので、用途に合わせて使う。

first();

モデルの最初のレコードを、オブジェクト形式で取得する。

find();

引数にidを指定して、特定のレコードを、オブジェクト形式で取得する。

get();

モデルのレコードを、コレクション(配列と思っていい)形式で取得する。
配列なので、取得した値はforeachで回して出力する。
whereを使って絞り込み検索などもできる。

index.php
$user = User::where('name', 'tarou')->get();
dd($user);
index2.php
$users=User::whereIn('phone', [0, 1])->get();
return view('user.index', compact('users'));

※whereInは、指定した値が「含まれている」(部分一致)レコードを取得。条件を配列形式で指定。

all();

モデルのレコードを、全件、コレクション形式で取得する。
配列なので、取得した値はforeachで回して出力する。

controller.php
$users = User::all();
return view('user.index', compact('users'));
blade.php
@foreach($users as $user)
  <table>
    <tr>
      <td>{{$user->name}}</td>
      <td>{{$user->email}}</td>
    </tr>
  </table>
@endforeach

※get();とall();は、->toArray();で、配列に変換できる。

index.php
$user = User::all();
$userArray = $user->toArray();

条件検索の場合はget()

クエリビルダでは、条件をかけてSQLを実行する場合、get()を使う。
全件取得でも条件がかけられていれば、all()ではなくget()。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?