I found a solution that worked for me.
I always define relationships with the correct namespace, for example in Calendar:
public function events() {
return $this->hasMany('App\Models\Event');
}
My problem consisted out of 2 complications:
$calendar->user()
with themorphTo(...)
function was not working because my models were in a namespace, andmorphTo(...)
had no way of giving this namespace.$salesman->calenders()->get()
returned and empty list, although my relations in the database were there. I found out this is because of bindings with the query.
Solution for 1. : Writing a custom morphTo(...)
function in Calendar to override the one of Laravel. I used the source of Laravels morphTo(...)
as a base. The final statement of this function is return $this->belongsTo($class, $id);
There $class
must be the namespaced class name. I used basic string operations to pull that off.
Solution for 2. : Writing a custom morphMany(...)
function in Salesman and letting it return a MyMorphMany(...)
similar to what Polymorphic Eloquent relationships with namespaces described.
The problem here is that $query
that is passed to the MyMorphMany
constructor has the wrong (namespaced) binding. It will look for where user_type = "App\\Models\\Salesman"
.
To fix this I used a custom getResults()
function in MyMorphMany
which overrides the default Laravels implementation, there I changed the bindings to use the correct, un-namespaced lower cased, class name. Then I called this getResults()
function in the get()
function of the MyMorphMany
class.
I used $query->getBindings()
and $query->setBindings()
to correct the bindings.
Hope this saves someone else a few days of work, like it would have saved me :)