I have multiple tables that will be tagged so someone here pointed me in the direction of Polymorphic Many to Many relationships. I read the documentation and watched Jeffreys video. My tags and tags and taggables table are set up the same as his in the video.
tags( id, name)
taggables(tag_id, taggable_id, taggable_type)
I created the models as shown in his video:
// app\Product.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
protected $fillable = [
'code_id',
'title',
'slug',
'body',
'display',
'new',
'published_at',
'image_id',
'excerpt'
];
public function categories() {
return $this->belongsToMany('App\Category');
}
public function status()
{
return $this->belongsTo('App\Status', 'display', 'id');
}
public function image()
{
return $this->belongsTo('App\ImageModel');
}
public function codes()
{
return $this->hasMany('App\Code');
}
public function tags()
{
return $this->morphToMany('App\Tag', 'taggable');
}
}
// app\Tag.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Tag extends Model
{
public function articles()
{
return $this->morphedByMany('App\Article', 'taggable');
}
public function anglers()
{
return $this->morphedByMany('App\Angler', 'taggable');
}
public function products()
{
return $this->morphedByMany('App\Product', 'taggable');
}
public function videos()
{
return $this->morphedByMany('App\Video', 'taggable');
}
}
I have a textarea called tags in a view, My form submits and astores all the other relevant information. when it comes to my tags it inserts records into taggables table with a blank tag id and nothing is recorded in the tags table.
my Method:
public function update(Request $request, $slug)
{
$product = Product::where('slug', $slug)->firstOrFail();
$request->merge([
'slug' => str_slug($request->get('title'))
]);
$product->fill($request->input())->save();
//sync categories array
$product->categories()->sync($request->get('categories'));
// use helper function tags_to_array to turn string into array and remove whitespace
$product->tags()->sync(tags_to_array($request->get('tags')));
return redirect(route('dashboard.products'));
}
my tags_to_array helper function:
function tags_to_array($string)
{
$array = explode(',', $string);
$result= array();
foreach($array as $tag){
$result[] = trim($tag);
}
return $result;
}
if I enter 3 keywords seperated by commas I recieve 3 records in taggables with blank tag ids and 0 records in tags.
Am I missing something?
NOTE: for anyone reading this thread, I accepted @bobbybouwmann first reply as the correct answer as that is technically what had to happen, how ever I had to change a few other things to get everything working as should so read rest of thread.