LoginSignup
0
0

More than 1 year has passed since last update.

Laravel課題・ルーティングパラメータ

Last updated at Posted at 2021-06-08

image.png

ルート

/items/{id}

に GET でアクセスすると、

商品の配列 $items のうち、該当のインデックス(配列のキー)の商品の商品名, 価格が表示させる。

該当のインデックスの商品が存在しない場合は「該当の商品は存在しません。」と表示させる。

該当のインデックスが配列内に存在するかを確認するにはarray_key_existsを活用する。

@ifを使って、商品が取得できた場合とできなかった場合の表示切り替えを行う。

リクエストメソッド: GET
URL: /items/{id}
アクション: SampleController@showItem
ビュー: samples.show_item

ルーティング

/アプリ名/routes/web.php

<?php
Route::get('/items/{id}', 'SampleController@showItem');

コントローラー

/アプリ名/app/Http/Controllers/showItem.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;

class SampleController extends Controller{

  public function showItem($id){
    $items = [
    [
        'name' => 'みかん',
        'price' => 200,
    ],
    [
        'name' => 'バナナ',
        'price' => 100,
    ],
    [
        'name' => 'キウイ',
        'price' => 150,
    ],
    [
        'name' => 'イチゴ',
        'price' => 500,
    ],
    ];

    if (array_key_exists($id, $items)) {
        $name = $items[$id]['name'];
        $price = $items[$id]['price'];
      return view('samples.show_item', [
        'name' => $name,
        'price'  =>  $price ,
      ]);
    } else {
       return view('samples.show_item', ['id' => $id,]);
    }

    // if(!isset($items[$id]) ){  
    //       return view('samples.show_item', ['id' => $id,]);
    // }
    // if(isset($items[$id]) ){  
    //     $name = $items[$id]['name'];
    //     $price = $items[$id]['price'];
    //     return view('samples.show_item', [
    //     'name' => $name,
    //     'price'  =>  $price ,
    //     ]);
    // }
  }
}

ビュー

/アプリ名/resources/views/samples/show_item.blade.php

@extends('layouts.logged_in')


@section('content')
<h1>課題ルーティングパラメータ</h1>

@if (isset($name))
  <dl>
      <dt>商品名</dt>
      <dd>{{ $name }}</dd>

      <dt>価格</dt>
      <dd>{{ $price }}</dd>

    </dl>
    @else
        <p>{{ $id }}:は該当の商品は存在しません</p>
    @endif

@endsection

ログイン後のレイアウト

/アプリ名/resources/views/layouts/logged_in.blade.php

@extends('layouts.default')

@section('header')
<header>
    <ul class="header_nav">
        <li>このサイトについて</li>
        <li>ユーザー設定</li>
        <li>プライバシーポリシー</li>
        <li>ログアウト</li>
    </ul>
</header>
@endsection

共通レイアウトファイル

/laravel_bbs/resources/views/layouts/default.blade.php

<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <title>@yield('title')</title>
    <style>
        .header_nav {
            display: flex;
            list-style: none;
            padding-left: 0;
        }
        .header_nav li {
            margin-right: 30px;
        }
    </style>
</head>
<body>
    @yield('header')
    @yield('content')
</body>
</html>
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