this code returns array of posts $brands = Input::get('posts');
Laravel - Many to Many Relationship
Hello everyone! I am trying to build a blog and my problem is how to connect the two tables (tags and posts) and store their ID's in my pivot table.
tags table: id name posts table: id name
post_table id post_id tag_id
I have already stored some values to my tag and post table. All I want to do is to get id from the post table and also from my tag table and connect them through many to many relationship.
2018_03_17_221539_create_tags_table.php
Schema::create('tags', function(Blueprint $table){
$table->increments('id');
$table->string('name');
$table->timestamps();
});
2018_03_17_221539_create_posts_table.php
Schema::create('posts', function(Blueprint $table){
$table->increments('id');
$table->string('name');
$table->timestamps();
});
2018_03_17_221539_create_post_tag_table.php
Schema::create('post_tag', function(Blueprint $table){
$table->increments('id');
$table->integer('post_id')->unsigned();
$table->foreign('post_id')->references('id')->on('posts');
$table->integer('tag_id')->unsigned();
$table->foreign('tag_id')->references('id')->on('tags');
$table->timestamps();
});
Tag Model
public function tags(){
return $this->belongsToMany('Tag', 'post_tag', 'post_id', 'tag_id');
}
PostModel
public function posts(){
return $this->belongsToMany('Post', 'post_tag', 'post_id', 'tag_id');
}
controller
public function store(Request $request)
{
$brands = Input::get('posts');
$brands->tags()->sync($request->tags, false);
return Redirect::back();
}
route
Route::post('brand/create', 'AdminController@store')->name('brand/create');
views
{{Form::open(array('url'=>'brand/create', 'method' => 'post', 'files'=>true))}}
<div class="form-group">
<label for="">Post</label>
<select name="posts[]" id="brands" class="input-sm">
@foreach($postsas $post)
<option value="{{$post->id}}">{{$post->name}}</option>
@endforeach
</select>
</div>
<div class="form-group">
<label for="">Category</label>
<select name="tags[]" class="input-sm">
@foreach($tagsas $tag)
<option value="{{$tag->id}}">{{$tag->name}}</option>
@endforeach
</select>
<a href="#" class="btn btn-danger btn-xs btn-remove-cat">Remove</a>
</div>
<button class="btn btn-sm btn-primary">Save</button>
{{Form::close()}}
I got this error
(1/1) FatalThrowableError Call to a member function tags() on array.
Thanks!
Please or to participate in this conversation.