Reputation: 445
I'm making simple tagging function in my laravel project. I've made table tags
id | tag
also I have table items
id | title | description
and third table item_tag
which will hold the id of item
and id of tag
In my Item model I've added this relation
public function tags() {
return $this->belongsToMany('App\Tag', 'item_tag');
}
and the relation in Tag model
public function itemTags() {
return $this->belongsToMany('App\Item', 'item_tag');
}
Item creating controller has create()
for the view and store()
for storing item
public function create(){
$allTags = Tag::all();
return view('items.create', compact('allTags'));
}
public function store( ItemRequest $request ){
$item = new Item;
$item->title = $request['title'];
$item->description = $request['description'];
$item->save();
return redirect()->route('items');
}
On form tags selection with multiple ( not sure if is correct way of doing it like this )
<div class="form-group">
{!! Form::label('tags', 'Tags', array('class'=> 'col-sm-2 control-label')) !!}
<div class="col-sm-10">
<select name="tags[]" class="form-control select2" id="tags" multiple>
@foreach($allTags as $tag)
<option value="{!!$tag->id!!}">{!!$tag->tag!!}</option>
@endforeach
</select>
</div>
</div>
My question is how to grab and save tags id and item id in pivot table? And then show tags on the page on the item?
Update
in dd($item)
I see this in relations
#relations: array:3 [▼
"tags" => Collection {#330 ▼
#items: array:1 [▼
0 => Tag {#329 ▼
#table: "tags"
#primaryKey: "id"
#fillable: array:1 [▶]
#connection: null
#keyType: "int"
#perPage: 15
+incrementing: true
+timestamps: true
#attributes: array:10 [▼
"id" => 5
"tag" => "testTag"
"title" => null
"subtitle" => null
"page_image" => null
"meta_description" => null
"layout" => null
"reverse_direction" => null
"created_at" => "2017-01-25 06:52:59"
"updated_at" => "2017-01-25 06:52:59"
]
}
]
}
]
Upvotes: 2
Views: 927
Reputation: 163798
Usually, you want to detach all tags from an item and attach only ones that user has added in the form. In this case, use sync()
method.
The sync method accepts an array of IDs to place on the intermediate table. Any IDs that are not in the given array will be removed from the intermediate table. So, after this operation is complete, only the IDs in the given array will exist in the intermediate table
For example:
$item = new Item;
$item->title = $request['title'];
$item->description = $request['description'];
$item->save();
// If some tags are new, you should create them here first and get their IDs from a DB.
$item->tags()->sync($request->tags);
Upvotes: 4