Reputation: 33690
So I am trying to create a taggable
table which enables multiple models
to have tags associated with them and felt that Laravel's Polymorphic relationships would be the way to go.
Unfortunately I can't seem to get them working in the following setup. As I receive the following error when running php artisan migrate:refresh --seed
.
{"error":{"type":"Symfony\\Component\\Debug\\Exception\\FatalErrorException","message":"Class name must be a valid object or a string","file":"...\\vendor\\laravel\\framework\\src\\
Illuminate\\Database\\Eloquent\\Model.php","line":527}}
I believe the issue is due to the fact that the Taggable
model has the same morphTo
named as outlined below. Since changing this fixes the issue. Why does this cause a problem?
Taggable model
class Taggable extends Eloquent {
protected $table = 'taggable';
public function taggable()
{
return $this->morphTo();
}
}
Track model
class Track extends Eloquent {
protected $table = 'tracks';
protected $fillable = array('title', 'year', 'image');
protected $guarded = array('id');
public function playlists()
{
return $this->belongsToMany('Playlist');
}
public function tags()
{
return $this->morphMany('Taggable', 'taggable');
}
}
Tag model
class Tag extends Eloquent {
protected $table = 'tags';
protected $fillable = array('title', 'description');
protected $guarded = array('id');
}
Migration
Schema::create('taggable', function(Blueprint $table)
{
$table->increments('id');
$table->integer('taggable_id');
$table->string('taggable_type');
$table->integer('tag_id');
$table->timestamps();
});
DatabaseSeeder Snippit
...
DB::table('taggable')->delete();
$track1 = Track::find(1);
$idm = Tag::find(1);
$track1->tags()->create(array('tag_id' => $idm->id));
...
Any help would be much appreciated on this matter.
Upvotes: 2
Views: 2397
Reputation: 4012
Try simplifying your relationships - you appear to be using an intermediate table to allow for tag reuse - which is commendable but is complicating your issue.
Start with the Tag and Track models - add additional complexity after you have the basic polymorphic relationship working.
Also, the issue might be that you are using the same name for your Model as the actual relationship function is named. IE Taggable->taggable() vs Tag->taggable()
Upvotes: 2