skip to Main Content

I have 2 tables 1) users 2) user_companies.
A user belongs to or has one company,
A company has many users.
This is how I determined my relationships.
How can I pull company data for each user?
Attempt to read property "company" on string – is the error I am receiving with my setup.

Here is what I have tried so far and many other combinations but cant seem to figure out how to show the company name which is stored in the user_companies table under the company column. Not sure what I am missing here.

user model

    // Relationship between User and Company
    public function company()
    {       
        return $this->hasOne(Company::class, 'id','company_id');
        //return $this->belongsTo(Company::class, 'company_id');
    }

company model

    public function user()
    {
        return $this->hasMany(User::class);
    }

userController

    public function profile(User $user, Company $company)
    {
        $company = Users::with(['company']);
        //$company = Company::with('user')->find('33');
        
        return view('admin.users.profile', compact('user', 'company'));
    }

blade file

{{ $user->company->company }}

migration file (just added new column FK)

Schema::table('users', function (Blueprint $table) {

            $table->integer('company_id')->nullable()->unsigned();
            $table->foreign('company_id')
            ->references('id')
            ->on('user_companies')
            ->onDelete('cascade');
        });

2

Answers


  1. Chosen as BEST ANSWER

    I solved this by doing the following.

    user model

    public function company() :BelongsTo
    {
        return $this->belongsTo(Company::class, 'user_companies');
    }
    

    user controller

     public function profile(User $user, Company $company)
    {
      
        $company = Company::where('id', $user->company)->first();
        return view('admin.users.profile', compact('user', 'company'));
    }
    

    profile blade file

    {{ $company->name  }}
    

  2. First of all, you should change the relationship of user to company to belongsTo :

    // User.php
    public function company() :BelongsTo
    {
        return $this->belongsTo(Company:;class, 'company_id');
    }
    

    then eager load it by using with()

    User::with('company')->get();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search