Home > Mobile >  Laravel One to One Relationship get object result is null
Laravel One to One Relationship get object result is null

Time:03-02

Migration persons Table:

Schema::create('persons', function (Blueprint $table) {
        $table->id();
        $table->string("firstname");
        $table->string("lastname");
        $table->timestamps();
    });

Migration passports Table:

Schema::create('passports', function (Blueprint $table) {
        $table->id();
        $table->string("identifystring")->unique();
        $table->unsignedBigInteger("person_id");
        $table->timestamps();
        $table->foreign("person_id")->references("id")->on("persons")->onDelete("cascade");
    });

Person model:

class Person extends Model
{
    use HasFactory;

    protected $table ="persons";

    protected $fillable = [
        "firstname",
        "lastname"
    ];

    public function passport() {
        $this->hasOne(\App\Models\Passport::class, "passports.person_id","persons.id");
    }
}

Passport Model:

class Passport extends Model
{

use HasFactory;

    protected $table = "passports";

    protected $fillable = [
        "identifystring",
        "person_id"
    ];
}

execute Code:

$person = \App\Models\Person::findOrFail(2);
dd($person->passport());

Result is: null

CodePudding user response:

class Person extends Model
{
    use HasFactory;

    protected $table ="persons";

    protected $fillable = [
        "firstname",
        "lastname"
    ];

    public function passport() {
        $this->hasOne(\App\Models\Passport::class, "person_id", "id");
    }
}

CodePudding user response:

You did not return the relation. just return it:

public function passport() {
    return $this->hasOne(\App\Models\Passport::class, "passports.person_id","persons.id");
}

CodePudding user response:

As per the migrations written. In the Person model write

  public function passport() {
        return $this->hasOne(\App\Models\Passport::class, "person_id","id");
    }

and in the Passport model write

public function person() {
    return $this->belongsTo(\App\Models\Person::class, 'id', 'person_id');
}

Execute the code

$person = \App\Models\Person::findOrFail(2)->passport;
dd($person);
  • Related