Zenn
🐘

Laravel入門3 Request

2025/03/11に公開

前回の記事

https://zenn.dev/kate0418/articles/4783ab3f33b623

次回の記事

随時更新

Request

Requestとは

フォーム送信の入力値などのアクセス時のリクエスト情報

フォームの作成

top/index.blade.phpにフォームを記述

  • 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個でphpを記述 --}}
    {{-- route(ルーティング名) とすることでformからURLにアクセス可能 --}}
    <form action={{ route('top.index') }}>
        <label>名前</label>
        <input type="text" name="name">
        <label>メールアドレス</label>
        <input type="text" name="email">

        <button type="submit">送信</button>
    </form>
</body>
</html>

ルーティング名

  • web.php
// top.index のこと
Route::get('/top', [TopController::class, 'index'])->name("top.index");

フォームデータの受け取り

TopControllerindex関数でリクエストから入力値を取得

  • TopController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class TopController extends Controller
{
    // Request 変数名 で変数にリクエストが代入される
    // (今回は$requestにリクエストが代入される)
    function index(Request $request) {
        $age = 19;
        $skills = ["Python", "PHP", "JavaScript"];

        // リクエストからnameとemailを取得
        // inputのname属性がキーの名前になる
        // <input type="text" name="name">
        $name = $request["name"];
        $email = $request["age"];

        // nameとemailもviewに渡す
        return view("top.index", compact("name", "email", "age", "skills"));
    }
}

フォームデータの表示

top/index.blade.phpnameemailを表示

<!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>
    <form action={{ route('top.index') }}>
        <label>名前</label>
        <input type="text" name="name">
        <label>メールアドレス</label>
        <input type="text" name="email">

        <button type="submit">送信</button>
    </form>

    {{-- $nameが無い場合もあるので、if文で確認 --}}
    @if ($name)
        <p>名前: {{ $name }}</p>
    @endif

    {{-- $emailが無い場合もあるので、if文で確認 --}}
    @if ($email)
        <p>メールアドレス: {{ $email }}</p>
    @endif
</body>
</html>

http://localhost:8000/topで名前とメールアドレスを送信したときに表示されればOK

Discussion

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