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?

[Laravel]データベースからデータを取得してページに表示しよう!

Posted at

はじめに

laravelでデータベースからデータを取得してページに表示する方法を簡単に実装します。

実装

データベースの情報

⇩のようなFruitsというテーブルから「price」が「150」以下のデータを取得して表示したいと思います。
スクリーンショット 2025-01-14 7.12.10.png

コントローラーの作成

ターミナルで以下のコマンドを実行し、コントローラーを作成します。

php artisan make:controller FruitController

Fruitsテーブルの中で「price」が「150以下」のデータを選択して、取得し $fruits に格納します。
取得したデータをcompact()関数に渡し、indexビューをページに表示します。

<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\DB;

class FruitController extends Controller
{
    public function index()
    {
        $fruits = DB::table('fruits')
            ->where('price', '<=', 150)
            ->get();
        return view('index', compact('fruits'));
    }
}

ビューの作成

resources/views/フォルダの中に「index.blade.php」というファイルを作成し、以下のように編集します。

<!DOCTYPE html>
<html lang="ja">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Laravel</title>
</head>

<body>
    <p>値段が150円以下のものを表示します</p>
    @foreach ($fruits as $fruit)
        <p>{{ $fruit->name }}</p>
    @endforeach
</body>

</html>

ルートの設定→

/fruitsというURLにアクセスした時、先ほど作成したFruitControllerの「index」アクションが実行されるようにします。
routes/web.phpファイルを以下のように編集します。

use App\Http\Controllers\FruitController;

Route::get('/fruits', [FruitController::class, 'index']);

ページの確認

/fruitsにアクセスし、ページを確認します。
スクリーンショット 2025-01-14 8.08.43.png

さいごに

いかがだったでしょうか?
データベースの情報を取得して、ページに表示するために最低限必要なコードのイメージがつかめればと思います!

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?