laravel

ErrorException Undefined index: App\xxxと戦う。Laravel

laravel

テーブルへRequestの値を挿入したいのに。全然できない話。
なんとか先へ進めたけれど、理解はできてません。

動作環境

ざっくりMac El capitan
mysql@5.6
PHP7.2.5
Laravel Framework 7.6.2
ローカル環境です。

状況

問題のコントローラー

<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Table_check;

class TabletestController extends Controller
{
public function showTabletestPage()
{
return view(‘tabletest’); // resource/views/tabletest.blade.phpを表示
}

public function postTabletest(Request $request)
{
$validator = $request->validate([ // バリデーション
‘name’ => [‘required’, ‘string’, ‘max:20’],
‘email’ => [‘required’, ‘string’, ‘max:40’],
]);

Table_check::create([// テーブルへ挿入
‘name’ => $request->name,
‘email’ => $request->email,
]);
return back(); // ページに戻る
}
}

モデル

<?php
namespace App;
use Carbon\Traits\Timestamp;use Illuminate\Database\Eloquent\Model;

class Table_check extends Model{
    protected $fillable = [
       ‘name’, ‘email’,
    ];
    protected static function boot(){
    }
}

migrationの一部抜粋

public function up() {
Schema::create(‘table_checks’, function (Blueprint $table) {
$table->bigIncrements(‘id’);
$table->string(‘name’);
$table->string(‘email’)->unique();
$table->timestamp(‘created_at’)->default(DB::raw(‘CURRENT_TIMESTAMP’));
$table->timestamp(‘updated_at’)->default(DB::raw(‘CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP’));
});
}

(idの取り扱いは作成中で実際少し違うけどこんな感じ)

対応1 画面で入力した値は本当に取得できているのか確認

エラーのrequestタブからbodyを確認したところ、取得できていた。

もしrequestタブがない等あれば以下のコマンドを設置すると見れる。

print_r($_POST);

を問題のコントローラのメソッド内へ配置。

対応2 キャッシュクリアしてみる

ググって、キャッシュクリアのコマンドを一通り試した。

Laravel キャッシュクリア系コマンドなど

特に変化なし。

対応3【解決】なんとなくboot()メソッドをコメントアウト

該当箇所(index: App\xxx)のboot()ファンクションが使われていないのでコメントアウトしてみた。

//以下をコメントアウトした
//protected static function boot()
// {
// }

まさかのエラーなし。

英語の記事にはparent boot()の設定忘れちゃうよね、今日もこのエラー起きたよ。みたいなことが書かれていてboot()周りが怪しいのかなと疑っていたけれど意味がわからなくてスルーしていたが、まさかの消したら動きました。

どういうことなんだろう。解決したけど、もやる。
わかる方いたら教えていただきたいです。

参考サイト:Laravel 5.7 Undefined index: App\Company

1日以上このエラーで消えました。とりあえずよかった。

POSTED COMMENT

  1. MohannadNaj より:

    boot method in model should use the parent boot first.

    “`
    protected static function boot(){

    }
    “`

    To:
    “`
    protected static function boot(){
    parent::boot();
    }
    “`

    • Nakamoto より:

      Hi MohannadNaj,
      Thank you for a nice message and Sorry for late reply.

      Sorry for my lack of ability, I didn’t know that and still confusing…
      I’ll search it with your info, thanks

MohannadNaj へ返信する コメントをキャンセル

メールアドレスが公開されることはありません。 が付いている欄は必須項目です