LoginSignup
1
1

More than 3 years have passed since last update.

Laravelで入力したフォーム値をDBに登録する

Last updated at Posted at 2021-03-21

簡単な入力フォームを作り、DBに登録までを行う

1. ルーティング設定

web.php

<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    return view('welcome');
});

Route::get('/information', 'HogeController@create');

Route::post('/add', 'HogeController@add');

?>

2. テーブルの準備

$ php artisan make:migration create_hoge_table

テーブルを作成後、database/migrations配下にあるcreate_hoge_tableを確認する。

create_hoge_table.php
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateHogeTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('hoge', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->char('title', 255);
            $table->char('body', 255);
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('hoge');
    }
}

その後、artisanコマンドで下記を実行

$ php artisan migrate

下記画像のように、DBにテーブルが登録されていればOK!!

スクリーンショット 2021-03-21 22.35.03.png

3. モデル作成

$ php artisan make:model Models/hoge
Hoge.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Hoge extends Model
{
    protected $table = 'hoge';
    protected $fillable = ['title', 'body'];
    protected $dates =  ['created_at', 'updated_at'];
}

$fillableとは?

$fillable(代入可能)に配列を設定した上でprotectedすれば、配列内のカラムのみcreate()やupdate() 、fill()が可能になる。

4. Controller

artisanコマンドでController.phpを作成する。

$ php artisan make:controller HogeController
HogeController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Hoge;

class HogeController extends Controller
{
    public function create() {
        return view('create');
      }

    public function add(Request $request) 
    { 
        $post = new Hoge();
        $post->title = $request->title;
        $post->body = $request->body;
        $post->save();

        return redirect('/information');
     }

}

5. viewの作成

create.blade.php
<head>
  <meta charset="utf-8">
</head>

<form method="post" action="{{ url('/add') }}">
    {{ csrf_field() }}
    <p>
      <input type="text" name="title" placeholder="名前を入力してください">
    </p>
    <p>
      <textarea name="body" placeholder="生年月日を入力してください"></textarea>
    </p>
    <p>
      <input type="submit" value="Add">
    </p>
  </form>

上記のソースだと下記の画像のような、画面が表示される。
スクリーンショット 2021-03-21 23.49.25.png

  • formタグのactionでurlという機能を呼び出しているがこれはソースコードの下の方にある「追加」ボタンを押したあとに遷移する飛び先になる。

  • {{ csrf_field() }}を宣言することにより、POST, PUT, DELETEのリクエストをした際に認証済みユーザーのトークンと一致するか自動的にチェックしてくれる。

6. DBに入力した値が反映されていることを確認する

上記URLにアクセスし、任意の値を入力する。

スクリーンショット 2021-03-22 0.01.52.png

その後、入力したフォームの内容がDBに登録されていることを確認できた!
スクリーンショット 2021-03-22 0.03.31.png

http://127.0.0.1:8000/informationにアクセスした時にHogeControllerのcreateメソッドが呼ばれ、メソッド内のreturn view('create');でcreate.blade.phpを表示させている。

その後、画面上のAddを押下したときにHogeControllerのaddメソッドが呼ばれ、DBに登録ができた。

参考サイト

1
1
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
1
1