Problem:
When I have:
namespace Domain\Client;
use Domain\Address\Address;
use Illuminate\Database\Eloquent\Model;class Client extends Model {
public function addresses()
{
return $this->morphMany(Address::class, ‘owner’);
}
}—-
namespace Domain\Customer;class Customer extends \Domain\Client\Client
{
}
The “addresses” relationship doesn’t work because the class morphMany is getting (by default) the class name “Domain\Customer\Customer” and in reality, it must get the “father class” which is “Domain\Client\Client”.
I propose to solve this problem by adding a parameter to inform the “father class” in the following way, extends class “Model of Laravel and add its methods”:
/**
* Define a polymorphic one-to-one relationship.
*
* @param string $related
* @param string $name
* @param string $type
* @param string $id
* @param string $localKey
* @param \Illuminate\Database\Eloquent\Model $parent
* @return \Illuminate\Database\Eloquent\Relations\MorphOne
*/
public function morphOne($related, $name, $type = null, $id = null, $localKey = null, Model $parent = null)
{
$instance = new $related;list($type, $id) = $this->getMorphs($name, $type, $id);
$table = $instance->getTable();
$localKey = $localKey ?: $this->getKeyName();
if (is_null($parent)) {
$parent = $this;
}return new MorphOne($instance->newQuery(), $parent, $table.’.’.$type, $table.’.’.$id, $localKey);
}public function attributesToArray()
{
$attributes = parent::attributesToArray();
$dates = $this->getCastDates();
foreach ($dates as $key) {
if (!array_key_exists($key, $attributes)) {
continue;
}$attributes[$key] = Carbon::parse($attributes[$key])->format(‘Y-m-d’);
}
Now
way to solve with the proposed amendment would inform it in class father, like this:
namespace Domain\Client;
use Domain\Address\Address;
use You-Model-With-Methods;class Client extends You-Model-With-Methods {
public function addresses()
{
return $this->morphMany(Address::class, ‘owner’, null, null, null, new Self);
}
}
It was proposed in the framework Laravel one PR, if accepted will not need to do this, you already have a native solution.
https://github.com/laravel/framework/pull/15471