Search code examples
phplaraveleloquenteloquent-relationship

Laravel one to one relationship not work only show null message


I have 2 tables in my database and tried to get data from them, this is my database schema :

---------------       ---------------
|     pg      |       |   phone     |
===============       ===============
|    id       |       |    id       |
|    name     |       |    telp     |
|    address  |       |    pg_id    |
===============       ===============

phone table is belonging to pg, I have pg model like this :

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Pg extends Model{
    protected $table = "pg";

    public function telepon(){
        return $this->hasOne('App\Models\Phone', 'pg_id', 'id');
    } 
}

and this is my phone model :

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Phone extends Model{
    protected $table = "phone";

    public function pg(){
        return $this->belongsTo('App\Models\Pg', 'pg_id', 'id');
    }
}

This is my code inside Controller to get data :

$pg = Pg::find(1);
return view('inpform', ['data' => $pg]);

inside my view I dump data but the result was NULL, if I change code to :

$pg = Pg::all();
return view('inpform', ['data' => $pg]);

it shows data from table pg only, I want a relation between them.


Solution

  • You have defined the relationships, but this does not automatically mean they will be associated with the model. You have two choices for eager loading these relationships. You can alter your controller code to request the relationships be loaded:

    $pg = Pg::with('telepon')->find(1);
    // or
    $pg = Pg::with('telepon')->get();
    

    Or, if you will always want this data, you can add it to the model's $with property.

    <?php
    
    namespace App\Models;
    
    use Illuminate\Database\Eloquent\Model;
    
    class Pg extends Model
    {
    
        protected $table = "pg";
    
        public function telepon()
        {
            return $this->hasOne(Phone::class);
        } 
    
        /**
         * The relationships that should always be loaded.
         *
         * @var array
         */
        protected $with = ['telepon'];
    }
    

    This will result in the relationship being loaded every time you access any Pg models.