データベースからデータを取り出して表示する。
データベースに格納されているデータを取り出してブラウザに表示する方法を解説します。
まず、モデルクラスを作成します。
$ cd /aho $ php artisan make:model Livers $ cd ./app/Models $ vi Livers.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Livers extends Model
{
use HasFactory;
protected $table = "T_LIVERS"; //-- 紐づけるデータベースのテーブルを指定
}
次にコントローラーを作成します。
$ cd /aho $ php artisan make:controller LiverController $ cd ./app/Http/Controllers $ vi LiverController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Livers; ##-- <- モデルクラスを指定する。
class LiverController extends Controller
{
public function index()
{
$results = json_decode(\DB::table('T_LIVERS')->get()); ##-- DBからデータを取得する。
$result = array(); #補助用変数
return view('liver.index', compact('results', 'result'));
##-- view関数の第二引数に上記の$results, $resultを渡すために、compact('results', 'result')を指定
}
}
~
最後にビューを作成します。
$ cd /aho $ cd ./resources/views $ mkdir liver $ cd ./liver $ touch ./index.blade.php $ vi ./index.blade.php
<html>
<head>
<title>Test</title>
</head>
<body>
<h1>Hello, World</h1>
<table>
<tr>
<th>Column1</th>
<th>Column2</th>
<th>Column3</th>
<th>Column4</th>
<th>Column5</th>
<th>Column6</th>
<th>Column7</th>
</tr>
@foreach($results as $result) <!-- コントローラーでcompactで渡した変数がそのまま参照可能 -->
<tr>
<th>{{$result->ID}}</th>
<th>{{$result->RoomNumber}}</th>
<th>{{$result->Name}}</th>
<th>{{$result->Uneatable}}</th>
<th>{{$result->RiceType}}</th>
<th>{{$result->RiceQuantity}}</th>
<th>{{$result->Comment}}</th>
</tr>
@endforeach
</table>
</body>
</html>
以下のように表示されます。

