記事投稿の際にあらかじめ用意されているタグ一覧からcheckboxで選択し、記事に紐付けたいのですが、その書き方がわかりません。
postsテーブル $table->increments('id'); $table->integer('user_id')->unsigned()->index(); $table->string('title'); $table->string('content'); $table->timestamps();
tagsテーブル $table->increments('id'); $table->string('tag_name'); $table->timestamps();
中間テーブル(posts_tagテーブル) $table->increments('id'); $table->integer('post_id')->unsigned()->index(); $table->integer('tag_id')->unsigned()->index(); $table->timestamps(); $table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade'); $table->foreign('tag_id')->references('id')->on('tags')->onDelete('cascade');
create.blade.php <h1>投稿ページ</h1> {!! Form::open(['route' => 'posts.store']) !!} <div class="form-group"> {!! Form::label('title', 'title') !!} {!! Form::text('title', null,['class' => 'form-control']) !!} </div> <div class="form-group"> {!! Form::label('content', 'content') !!} {!! Form::textarea('content', null, ['class' => 'form-control']) !!} </div> <div class="form-group"> @foreach($tags as $tag) {!! Form::label('tags', $tag->tag_name) !!} {!! Form::checkbox('tags', $tag->id) !!} @endforeach </div> {!! Form::submit('投稿', ['class' => 'btn btn-lg btn-seccess']) !!} {!! Form::close() !!} </div> </div>
controllerのstoreアクション public function store(Request $request) { $request->user()->posts()->create([ 'title' => $request->title, 'content' => $request->content, ]); $post->tags()->attach(request()->tags); return redirect()->back(); }
Postモデル public function tags() { return $this->belongsToMany(Tag::class, 'posts_tag', 'post_id', 'tag_id')->withTimestamps(); } Tagモデル public function tag_posts() { return $this->belongsToMany(Post::class, 'posts_tag', 'tag_id', 'post_id')->withTimestamps(); }
postsテーブルにタグの値を入れるカラムは用意していないので、$request->user()->posts()->create([~~~]);
外に適切な記述をする必要があると思うのですが方法がわかりません。
tinkerでは記事とタグの紐付けに成功しています。
ご教授いただきたく存じます。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/11/28 12:47
2018/11/29 05:09
2018/11/29 07:00