2 years ago

#59270

test-img

Favour Max-Oti

Relationship is returning null even when from the database the data exists

I have been getting an empty array when I query this model relationship for data. I have tried pulling all the data associated with the model from the database and I still do not get the data even though physically the records are in the database. Please can anyone help me fix this?

Here is my model relationship code

    public function business()
    {
        return $this->businesses()->first();
    }

   public function businesses()
    {
        return $this->belongsToMany(Business::class, 'business_user', 'business_id', 'user_id')->withTimestamps();
    }

Here is my resource to pull the data

public function toArray($request)
    {
        return [
            'name' => ($this->middle_name) ? "{$this->first_name} {$this->middle_name} {$this->last_name}" : "{$this->first_name} {$this->last_name}",
            'email' => $this->email,
            'phone_number' => $this->phone_number,
            'next_of_kin' => $this->kin,
            'gender' => $this->gender,
            'image' => $this->image,
           'address' => ($this->business->address) ?: [],
            'business' => ($this->business) ?: [],
            'credits' => ($this->business->credits) ?: [],
            'guarantors' => ($this->business->guarantors) ?: [],
            'verified' => ($this->business->address->verified) ?: [],
            'utility' => ($this->business->address->state_regions) ?: [],
        ];
    }

Since the relationship I am querying returns an empty array, all the data depending on it throws an error whenever I try to access them.

php

eloquent

laravel-7

eloquent-relationship

0 Answers

Your Answer

Accepted video resources