5
4

More than 3 years have passed since last update.

Laravelでチェックボックスの値を取得しold関数でチェックを保持

Last updated at Posted at 2020-02-03

概要

Laravel初心者(というかPHP自体の初学者ですが。。)が実務でアンケートフォームの作成を任されたので、自分用にメモを残します。

ルーティング

web.php
<?php

Route::get('/', 'FormController@form')->name('form');
Route::post('/confirm', 'FormController@confirm')->name('confirm');
Route::post('/complete', 'FormController@complete')->name('complete');

モデル

Form.php
<?php
namespace App;

use Illuminate\Database\Eloquent\Model;

class Form extends Model
{
    protected $fillable = [
        'checkbox',
    ];

}

ビュー:入力画面

form.blade.php
@extends('layouts.default')
@section('content')

<form method="post" action="{{ route('confirm') }}">
  @csrf
  <div class="form-group">
    <div class="form-check">
      <input id="check1" type="checkbox" name="checkbox[]" value="選択肢1"{{ is_array(old("checkbox")) && in_array("選択肢1", old("checkbox"), true)? ' checked' : '' }}>
      <label class="form-check-label" for="check1">選択肢1</label>
    </div>
    <div class="form-check">
      <input id="check2" type="checkbox" name="checkbox[]" value="選択肢2"{{ is_array(old("checkbox")) && in_array("選択肢2", old("checkbox"), true)? ' checked' : '' }}>
      <label class="form-check-label" for="check2">選択肢2</label>
    </div>
    <div class="form-check">
      <input id="check3" type="checkbox" name="checkbox[]" value="選択肢3"{{ is_array(old("checkbox")) && in_array("選択肢3", old("checkbox"), true)? ' checked' : '' }}>
      <label class="form-check-label" for="check3">選択肢3</label>
    </div>
    @if ($errors->has('checkbox'))
      <span class="error">{{$errors->first('checkbox')}}</span>
    @endif
  </div>
  <button type="submit" class="btn btn-lg btn-primary">入力内容の確認</button>
</form>

@endsection

ビュー:確認画面

confirm.balde.php

@extends('layouts.default')
@section('content')

<form method="post" action="{{ route('complete') }}">
  @csrf
  <div class="form-group">
    <p class="confirm-input">{!! nl2br(e($checkbox)) !!}</p>
  </div>
  @foreach($inputs->getAttributes() as $key => $value)
      @if(isset($value))
          @if(is_array($value))
              @foreach($value as $subValue)
                  <input name="{{ $key }}[]" type="hidden" value="{{ $subValue }}">
              @endforeach
           else
              <input name="{{ $key }}" type="hidden" value="{{ $value }}">
          @endif
      @endif
  @endforeach
  <button type="submit" name="action" value="back" class="btn btn-lg btn-info">戻る</button>
  <button type="submit" name="action" value="submit" class="btn btn-lg btn-primary">送信</button>
</form>

@endsection

コントローラー

FormController.php

<?php

namespace App\Http\Controllers;

use App\Form;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class FormController extends Controller
{
    public function form()
    {
        return view('form');
    }

    public function confirm(Request $request)
    {
        //バリデーションを実行(結果に問題があれば処理を中断してエラーを返す)
        $rules = [
            'checkbox' => 'required',
        ];

        $messages = [
            'checkbox.required' => 'チェックを入れてください',
        ];

        $validator = Validator::make($request->all(), $rules, $messages);

        if ($validator->fails()) {
        return redirect(url("/"))
                ->withErrors($validator)
                ->withInput();
        }

        //フォームから受け取ったすべてのinputの値を取得
        $inputs = new Form($request->all());

        // 配列から文字列に
        $checkbox = '';
        if (isset($request->checkbox)) {
            $checkbox = implode("\n",$request->checkbox);
        }

        //入力内容確認ページのviewに変数を渡して表示
        return view('confirm', compact('inputs', 'checkbox'));
    }

    public function complete(Request $request)
    {
        $input = $request->except('action');

        if ($request->action === 'back') {
            return redirect()->action('FormController@form')->withInput($input);
        }

        // チェックボックス(配列)を改行コード区切りの文字列に
        if (isset($request->checkbox)) {
            $request->merge(['checkbox' => implode("\n", $request->checkbox)]);
        }

        // データを保存
        Form::create($request->all());

        // 二重送信防止
        $request->session()->regenerateToken();

        return view('complete');
    }

}


5
4
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
5
4