0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【備忘録】PHPでデータを配列にしてフォームを送信する方法

0
Last updated at Posted at 2026-02-23

こちらのサイトを真似して、複数の入力フォームの値を
配列に入れて保存できるようにしました。

1. nameプロパティに配列を指定する

create_blade.php
 <form action ="{{ route('books.store') }}" method="post" enctype="multipart/form-data">
        @csrf
        <dl>
            <dt>表紙</dt>
            <dd><input type="file" name="image[]"></dd>
            <dt>タイトル</dt>
            <dd><input type = "text" name="title[]"></dd>
            <dt>著者</dt>
            <dd><input type = "text" name="author[]"></dd>
            <dt>出版日</dt>
            <dd><input type = "date" name="published_on[]"></dd>
        </dl>
        <dl>
            <dt>表紙</dt>
            <dd><input type="file" name="image[]"></dd>
            <dt>タイトル</dt>
            <dd><input type = "text" name="title[]"></dd>
            <dt>著者</dt>
            <dd><input type = "text" name="author[]"></dd>
            <dt>出版日</dt>
            <dd><input type = "date" name="published_on[]"></dd>
        </dl>
        <button type="submit">登録する</button>
    </form>

image.png

この時に送られてくるパラメータでtitle, authorといったnameで指定した配列に
入力した値が入っている
image.png

2. 入力した値をコントローラで受け取って保存の処理をする

BookController.php
public function store(Request $request)
    {
        //配列を受け取る
        $images       = $request->file('image');
        $titles       = $request->title;
        $authors      = $request->author;
        $publishedOns = $request->published_on;

        //各値のセット, 保存をループ処理する
        foreach ($titles as $key => $title){
            $book = new Book();
            $book -> title        = $title; 
            $book -> author       = $authors[$key];
            $book -> published_on = $publishedOns[$key];

            //画像の処理
            $image = $images[$key];
            $path  = $image->store('public/images');
            $book->image = $path;

            $book -> save();
        }
        return redirect(route('books.index'));
    }

受け取った配列をforeachを使って、データを1つずつ取り出し、
それぞれのデータを使って、データベースに新しいレコードを作成・保存する

3.保存した結果
image.png

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?