LoginSignup
0
0

More than 1 year has passed since last update.

laravel クッキーのサンプル

Posted at

ルーティング

/routes/web.php

<?php
Route::get('/cookie_sample', 'SampleController@cookieSample');

Route::post('/cookie_sample', 'SampleController@cookieDelete');

コントローラー

app/Http/Controllers/SampleController.php

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

class SampleController extends Controller{

      public function cookieSample(){

        $count = \Cookie::get('count', 0);
        $count++;

        \Cookie::queue('count', $count, 60 * 24 * 90);

        return view('samples.counter_sample', [
          'title' => 'クッキーを利用するサンプル',
          'count' => $count,
        ]);
      }

       public function cookieDelete(){

        \Cookie::queue(\Cookie::forget('count'));

        return 'cookieを削除しました。';
      }

}

ビュー

resources/views/samples/csv_sample.blade.php

@extends('layouts.default')

@section('title', $title)

@section('content')

<h1>{{ $title }}</h1>
@if($count === 1)
  <p>初めての訪問です</p>
@else
  <p>{{ $count }}回目の訪問です
@endif

<form method="post">
  @csrf
  <input type="submit" value="履歴を削除">
</form>

@endsection

共通レイアウトファイル

<!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;
        }
        /* エラーメッセージ用のスタイル */
        .error {
          color: red;
        }
    </style>
</head>
<body>
    @yield('header')

    {{-- エラーメッセージを出力 --}}
    @foreach($errors->all() as $error)
      <p class="error">{{ $error }}</p>
    @endforeach

    @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