問題点 : laravel9で、DBからデータを取り出したいがエラーがでて取り出せない。存在しないと表示される。
実装しようとしているもの: いいね機能を実装しようと考えており、こちら
のサイトを参考にしているのですが、いいねを何回も押せてしまう仕様になってしまったため確認したらいいねのDB nicesテーブルのuser_idの部分がNULLになっていたため修正を試みているところ上記のエラーにぶつかりました。
php
1 2//niceテーブルのマイグレーションファイル 3return new class extends Migration 4{ 5 /** 6 * Run the migrations. 7 * 8 * @return void 9 */ 10 public function up() 11 { 12 Schema::create('nices', function (Blueprint $table) { 13 $table->id(); 14 $table->unsignedBigInteger('blog_id')->nullable(); 15 $table->unsignedBigInteger('user_id')->nullable(); 16 $table->timestamps(); 17 }); 18 } 19・・・・
php
1 2//blogsテーブルのマイグレーションファイル 3return new class extends Migration 4{ 5 /** 6 * Run the migrations. 7 * 8 * @return void 9 */ 10 public function up() 11 { 12 if (!Schema::hasTable('blogs')) { 13 Schema::create('blogs', function (Blueprint $table) { 14 $table->id(); 15 $table->string('title',100); 16 $table->text('content'); 17 $table->text('advise'); 18 $table->text('twitterUrl'); //ツイッターのurlを記載 19 $table->timestamps(); //日付 20 $table->foreignId('user_id')->constrained()->onDelete('cascade'); //ユーザーID追加 21 }); 22 } } 23・・・・
php
1//ルーティング 2Route::get('/', 'App\Http\Controllers\BlogController@showList')->name('blogs');
php
1namespace App\Http\Controllers; 2 3use Illuminate\Http\Request; 4use App\Models\Blog; 5use App\Models\Nice; 6use App\Http\Requests\BlogRequest; 7 8//投稿内容を表示するメソッド 9public function showList(Blog $blogs){ 10 $blogs = Blog::all(); 11 $nice=Nice::where('blog_id', $blogs->id)->where('user_id', auth()->user()->id)->first(); 12 return view('blog.list', compact('blogs', 'nice')); 13}
あなたの回答
tips
プレビュー