コントローラーにデータベースの抽出を記入しviewに表示させる 2
①と②どちらを使うかは管理者の指示に従う
②モデルを使用せずコントローラーに直接データベースへのアクセスを書きviewに表示させる
●コントローラーにデータベースを読み込む
app/Http/Controllers/HelloController.php
use App\Models\Test;
use Illuminate\Support\Facades\DB;// DBを呼び出す

データベースを使用するために
use Illuminate\Support\Facades\DB;
と記入
resources/views/hello2.blade.php
public function index2(Request $request){
}

public functionを下にコピーしてファンクション名をindex2に変更
中は消しておく。
viewのhello.blade.phpを複製してhello2.blade.phpにリネームする
●select * from tests
app/Http/Controllers/HelloController.php
// index2メソッドに追加
$result=DB::table("tests")->get();
return view('hello2',compact(result));
// compact配列に追加してresultをviewに渡す



= select * from tests
resources/views/hello2.blade.php
@foreach ($result as $value)
    <p>{{$value->name}}</p>
@endforeach



= foreach ($result as $value)
●select * from tests where id=2
app/Http/Controllers/HelloController.php
// index2メソッドに追加
$resultfind=DB:table("tests")->find(2)
return view('hello2',compact('str',str2',result,resultfind));
// compact配列に追加してresultfindをviewに渡す



= select * from tests where id=2
resources/views/hello2.blade.php
<p>{{$resultfind->name}}</p>

←findを使用した場合、配列ではなくデータ1つをとってくるので
配列を並べるためのforeachなどは使えない
●select * tests where sei=1
app/Http/Controllers/HelloController.php
// index2メソッドに追加
$resultwhere=DB::table("tests")->where('sei','=',1)->get();
return view('hello2',compact('str',str2',result,resultfind,resultwhere));
// compact配列に追加してresultwhereをviewに渡す



= select * tests where sei=1
resources/views/hello2.blade.php
@foreach ($resultwhere as $value)
    <p>{{$value->name}}</p>
@endforeach



= foreach ($resultwhere as $value)
プレビューで確認する