Zenn
🐘

Laravel入門2 bladeディレクティブ

2025/03/11に公開

前回の記事

https://zenn.dev/kate0418/articles/14bdd10a80446c

次回の記事

https://zenn.dev/kate0418/articles/94c9f2e8914d84

bladeディレクティブ

bladeディレクティブとは

laravelではControllerからviewに対して、PHP変数を渡すことができます
渡された変数を使ってbladeファイル内では、if文やfor文などを使用できます
↪︎ この構文をbladeディレクティブという

viewでPHP変数を使う準備

  1. TopController.phpからviewにage, skillsを渡す。
    (今回は年齢[age]と特技[skills]を渡すようにする)
  • TopController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class TopController extends Controller
{
    function index() {
        $age = 18; // ageを定義
        $skills = ["Python", "PHP", "JavaScript"]; // skillsを定義

        // viewの第2引数には連想配列を指定することでviewに変数を渡すことができる
        return view("top.index", compact("age", "skills"));

        // compact関数を使用しているが、以下と意味は同じ
        // return view("top.index", [
        //     "age" => $age,
        //     "skills" => $skills
        // ]);
    }
}

表示

  • top/index.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <h1>トップページ</h1>
    {{-- 中括弧2つで囲むことによって変数を表示可能 --}}
    <p>{{$age}}</p>
    <p>{{$skills[0]}}</p>
</body>
</html>

条件分岐

  • top/index.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <h1>トップページ</h1>
    @if ($age >= 20)
        <p>お酒が飲めます</p>
    @elseif ($age >= 18)
        <p>免許が取れます</p>
    @else
        <p>未成年です</p>
    @endif
</body>
</html>

ループ

  • top/index.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <h1>トップページ</h1>
    @foreach ($skills as $skill)
        <p>{{ $skill }}</p>
    @endforeach

    @for ($i = 0; $i < 5; $i++)
        <p>{{ $i }}</p>
    @endfor
</body>
</html>

Discussion

ログインするとコメントできます