laravelでCRUD機能を実装したい
現在laravel php 5.8でCRUDの処理を学んでいます。
users tableのuseridをkeyにして、addresses tableにuserの住所情報を追加する処理を
行いたいです。
laravelでデータのinsertやupdate,deleteの処理を行いたいのですが、
下記のソースを実行してもデータがテーブルに入りません。
はじめにuser情報は手動で入れたので、id=1のユーザーはテーブル内に存在しています。
テーブルのmigrateは完了し、カラムの追加などはうまくいっています。
データが挿入されない原因を教えていただくと助かります。
php laravel 5.8
users_table
php
public
1 { 2 Schema::create('users', function (Blueprint $table) { 3 $table->Increments('id'); 4 $table->string('name'); 5 $table->string('email')->unique(); 6 $table->timestamp('email_verified_at')->nullable(); 7 $table->string('password'); 8 $table->rememberToken(); 9 $table->timestamps(); 10 }); 11 } 12コード
addresses table
php
1public function up() 2 { 3 Schema::create('addresses', function (Blueprint $table) { 4 $table->Increments('id'); 5 $table->integer('user_id')->unsigned()->nullable(); 6 $table->string('name'); 7 $table->timestamps(); 8 }); 9 }
app/user.php
php
1public function address(){ 2 return $this->hasOne('App\Address', 'foreign_key'); 3 }
app/address.php
php
1protected $fillable = [ 2 'name' 3 ];
routes/web.php
php
1use App\User; 2use App\Address; 3 4Route::get('/', function () { 5 return view('welcome'); 6}); 7 8Route::get('/insert', function(){ 9 $user = User::findOrFail(1); 10 $address = new Addresses(['name'=>'1234 Houston av NY NY 234']); 11 $user->address()->save($address); 12}); 13 14
app/user.phpで、
php
1public function address(){ 2 return $this->hasOne('App\Address', 'foreign_key'); 3 } 4 5public function address(){ 6 return $this->hasOne('App\Address'); 7 }
の両方を試しました。
環境はmacでMAMPのlocal hostでmy sqlに接続しています。