Laravel One to One Relationship get object result is null

Viewed 39

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

4 Answers
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");
    }
}

You did not return the relation. just return it:

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

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);

Use this code.

In your Person Model

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

In your passport model

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

Then try to pass the relation again by doing the same thing

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