devhamx
6 months ago
283
10
Eloquent

the morphOne relation always return null

Posted 6 months ago by devhamx

im setting up a One To One (Polymorphic) like this

Models

class Payement extends Model
{
    protected $table = 'payements';
    protected  $primaryKey = 'id';

    public function commentable()
    {
        return $this->morphTo();
    }
}

class Recu extends Model
{
    protected $table = 'recus';
    protected  $primaryKey = 'id';  

    public function payement()
    {
        return $this->morphOne('App\Payement', 'payementable');
    }
}

Database

Schema::create('recus', function (Blueprint $table) {
            $table->bigIncrements('id');
        });

Schema::create('payements', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->double('montant');
            $table->string('numero')->unique();
            $table->morphs('payementable');
            $table->timestamps();
        });

this is working

App\Payement::find(1)->payementable; 

this return null

App\Recu::find(1)->payement;

and this return empty collection

App\Recu::find(1)->payement()->get()

data in the tables https://imgur.com/a/vNH3T7t

Please sign in or create an account to participate in this conversation.