Home > OS >  How to get information from 3 separate tables in Laravel
How to get information from 3 separate tables in Laravel

Time:01-10

I have a table called users that stores user information and each user can have multiple business accounts that are stored in separate tables.

Models:

User:

id

name

UserProviderAccount:

id

user_id

bussiness_name

bussiness_tell

bussiness_address

UserCompanyAccount

id

user_id

company_name

company_size

UserInfluencerAccount:

id

user_id

name

website

follower_count

Tables Relations :

User :

    public function providers(): HasMany
    {
        return $this->hasMany(UserProviderAccount::class);
    }
    public function companies(): HasMany
    {
        return $this->hasMany(UserCompanyAccount::class);
    }
    public function influencers(): HasMany
    {
        return $this->hasMany(UserInfluencerAccount::class);
    }

I want to display the user's business accounts of all three types at once.

How do I do this?

CodePudding user response:

You just have to load the relationships

    public function show($id){
    //Here we will eager load all of the relationships for the specific user
    $user = User::where('id', $id)->with('providers, 'companies', 'influencers')->firstOrFail();

   
    return view('users.show', compact('user'));
  }

CodePudding user response:

You simply need to load and call the relationships as follows:

UserController: sample controller and function

public function show(User $user){
    //Here we will load all of the relationships for the specific user
    $user->load('providers', 'companies', 'influencers');

    //Assign the providers from user->providers
    $providers = $user->providers;
    
    //Assign the companies from user->companies
    $companies = $user->companies;
    
    //Assign the influencers from user->influencers
    $influencers = $user->influencers;

    //Send all of the data to the view
    return view('users.show', compact('user', 'providers', 'companies', 'influencers'));
}

users.show View: simplified version to show you concept.

<p>{{$user->name}}</p>

<p>The providers:</p>
<ul>
    @foreach($providers as $provider)
        <li>{{$provider->bussiness_name}}</li>
        <li>{{$provider->bussiness_tell}}</li>
        <li>{{$provider->bussiness_address}}</li>       
    @endforeach
</ul>

<p>The companies:</p>
<ul>
    @foreach($companies as $company)
        <li>{{$company->company_name}}</li>
        <li>{{$company->company_size}}</li>     
    @endforeach
</ul>

<p>The influencers:</p>
<ul>
    @foreach($influencers as $influencer)
        <li>{{$influencer->name}}</li>
        <li>{{$influencer->website}}</li>
        <li>{{$influencer->follower_count}}</li>        
    @endforeach
</ul>
  • Related