I've been at this for 5 hours now and can't seem to figure out the mistake. I'm using Polymorphic Many-to-Many Relations in Laravel 4.1.
A Job and an Event each can have a Tag and I've set up the stuff accordingly. But whenever I call
$job->tags
it returns empty.
I have these 3 classes (BaseModel extends Eloquent, namespace is always App\Models, I have to reference them in the e.g. "morphToMany" function, doesn't work with "use"):
class Job extends BaseModel {
public function tags()
{
return $this->morphToMany('\App\Models\Tag', 'taggable');
}
[...]
}
The Tag Model:
class Tag extends BaseModel {
public function jobs(){
return $this->morphedByMany('\App\Models\Job', 'taggable');
}
public function events(){
return $this->morphedByMany('\App\Models\Event', 'taggable');
}
[...]
}
The Event Model ("event" as in conference, seminar - has own namespace App\Models to avoid conflict):
class Event extends BaseModel {
[... nothing relevant yet ...]
}
In my JobsController I have (test case, job with ID 14 exists)
public function show($slug)
{
$job = Job::find(14);
return \View::make('jobs.show', ['job' => $job]);
}
and my app/views/jobs/show.blade.php
[...]
echo $job->name;
echo $job->company;
foreach($job->tags as $tag) {
echo $tag->name;
}
[...]
The first outputs work just fine and it show the $job->name and $job->company correctly, so it's reading from the jobs table correctly, but
$job->tags
returns empty AND $tag->name is never called. I have a tags and taggable table (MySQL), here are the relevant lines
taggables (table)
-> id->increments()
-> tag_id->integer()->unsigned()->index
->foreign('tag_id')->references('id')->on('tag')
-> taggable_id->integer()->unsigned()->index()
-> taggable_type->string()->index()
tags (table)
-> id->increments()
-> name->string()
-> slug->string()
Test 1
When I do
$jobs = Job::has('tags')->get();
in my JobsController.php view it actually only returns the jobs which have tags, so I'm a bit hopeful that it works a little bit.
Test 2
But when I try to get the tags e.g. in this index.blade.php case
foreach($jobs as $job){
foreach($job->tags as $tag){
echo $tag->name;
}
}
it goes into the $jobs loop just fine, but it doesn't go into the $job->tags loop. In my taggables table I have a dataset
taggables
id: 1
tag_id: 1 (exists)
taggable_id: 14 (via foreign key)
taggable_type: Job
I'm going nuts, can't figure out where the problem lies. Am I missing something?