I am using laravel one to one relation and getting the null value exception on the data from other table

22 Views Asked by At

I can access my holder class data but i can't seems to access data that is coming from devices table. i have used postman to check my api and it return the data ok and also when i print_r the data on blade.php file it is printing the devices table data too. but while accessing the devices's data using $holder->get_device->name or other field i am getting null exception error

class Device extends Model
{
    use HasFactory;
    protected $table = 'devices';
    protected $primaryKey = 'device_id';
    protected $fillable = ['name','price'];
    
    public function getHolder(){
        return $this->belongsTo(Holder::class, 'device_id');
    } 
}

class Holder extends Model
{
    use HasFactory;
    protected $table = 'holders';
    protected $primaryKey = 'holder_id';
    protected $fillable = ['name','budget','device_id'];


    public function getDevice(){
        return $this->hasOne(Device::class,'device_id');
    }
}


  @foreach ($holders as $holder)
          <tr>
              <th>{{$holder->name}}</th>
              <td>{{$holder->budget * 100000}}</td>
              <td>{{optional($holder->get_device->name)}}</td>
              <td>{{optional($holder->get_device->price)}}</td>
           </tr>
   @endforeach

Data format

{
   "holder_id": 1,
   "name": "name",
   "budget": 2,
   "device_id": 2,
   "get_device": {
        "device_id": 1,
        "name": "deviceName",
        "price": "0.8"
    }
}

I have already check the table value, there is no missing foriegn key use in holder table all keys are present in devices table.Moreover, i check on postman and on my blade file data is coming and is showing using print_r() on blade file.

0

There are 0 best solutions below