前提・実現したいこと
laravelで写真付き掲示板を実装しているのですが、投稿にuser_idが入らず、エラーが発生します。
psqlでidを見た結果(この1を投稿のuser_idに入れたいです)
psql -h laradock_postgres_1 -U default -d default default=# select id from public.user; id --- 1
発生している問題・エラーメッセージ
投稿時に下記が発生
62983038は多分githubのidだと思われる(githubログインを実装しているので、、)
Illuminate\Database\QueryException SQLSTATE[23503]: Foreign key violation: 7 ERROR: insert or update on table "posts" violates foreign key constraint "posts_user_id_foreign" DETAIL: Key (user_id)=(62983038) is not present in table "users". (SQL: insert into "posts" ("user_id", "user", "image_file_name", "image_title", "updated_at", "created_at") values (62983038, user1, qKnFVDnnnAMb8ItjeGvq8yqGxnNLMUsAQCe0PfEZ.jpeg, eeeeeeeeeeeeeeeee, 2020-09-09 ...
該当のソースコード
PostController.php
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Foundation\Auth\User; use App\Models\Post; use Illuminate\Support\Facades\Validator; use Illuminate\Support\Facades\Storage; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\DB; use App\Http\Controllers\Controller; use Socialite; class PostController extends Controller { public function index() { return view('post'); } //画像およびコメントアップロード public function upload(Request $request){ $validator = Validator::make($request->all(), [ 'file' => 'required|max:10240|mimes:jpeg,gif,png', 'comment' => 'required|max:191' ]); $file = $request->file('file'); $path = Storage::disk('s3')->putFile('/', $file, 'public'); $token = $request->session()->get('github_token', null); try { $user = Socialite::driver('github')->userFromToken($token); } catch (\Exception $e) { return redirect('login/github'); } $client = new \GuzzleHttp\Client(); $res = $client->request('GET', 'https://api.github.com/user/repos', [ 'auth' => [$user->user['login'], $token] ]); Post::create([ 'user_id' => $user->id, 'user' => $user->nickname, 'image_file_name' => $path, 'image_title' => $request->comment ]); return redirect('index'); } public function delete($id) { Post::find($id)->delete(); return redirect('index'); } }
2020_06_16_145959_create_posts_table.php
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreatePostsTable extends Migration { public function up() { Schema::create('posts', function (Blueprint $table) { $table->id(); $table->integer('user_id')->unsigned(); $table->foreign('user_id')->references('id')->on('users'); $table->string('user'); $table->string('image_file_name',100); $table->string('image_title',100); $table->timestamps(); }); } public function down() { Schema::dropIfExists('posts'); } }
試したこと
Post::create時に'user_id' => Auth::id()で試したがgithubでのログインなのでうまくいかなかった