I need to know how can I save the id of the post in my table post_tag
, column post_id
?Now, when I add a new post, in my table is saved only tag_id
, can you give me some help with that?I'm watching a tutorial but I'm stuck with this problem.Thank you.
create_post_tag_table
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePostTagTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('post_tag', function (Blueprint $table) {
$table->bigIncrements('id');
$table->bigInteger('post_id')->unsigned();
$table->foreign('post_id')->references('id')->on('posts');
$table->integer('tag_id')->unsigned();
$table->foreign('tag_id')->references('id')->on('tags');
});
}
}
PostsController with function store
public function store(Request $request )
{
$data = request()->validate([
'caption' => 'required|max:255',
'image' => 'required|image',
]);
$post = new Post;
$post->tags()->sync($request->tags, false);
$imagePath = request('image')->store('uploads', 'public');
$image = Image::make(public_path("storage/{$imagePath}"))->fit(1600, 1100);
$image->save();
auth()->user()->posts()->create([
'caption' => $data['caption'],
'image' => $imagePath,
]);
return redirect('/profile/' . auth()->user()->id);
}
create_tags_table
public function up()
{
Schema::create('tags', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->timestamps();
});
}
create_posts_table
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id');
$table->string('caption');
$table->string('image');
$table->timestamps();
$table->index('user_id');
});
}
Now, with this lines $post = new Post;
and $post->tags()->sync($request->tags, false);
my tag id is saved in tag_id
column, but my new post id from table posts
isn't.How can I save my post id in my post_id
table?