1

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.

  • 1
    I found the problem with my code: I did not set the relationship keys in the right order. public function businesses() { return $this->belongsToMany(Business::class, 'business_user', 'business_id', 'user_id')->withTimestamps(); } is supposed to be: public function businesses() { return $this->belongsToMany(Business::class, 'business_user', 'user_id', 'business_id')->withTimestamps(); } – Favour Max-Oti Jan 17 '22 at 07:03

0 Answers0