MLJezus
MLJezus

Reputation: 79

Laravel - Requesting data from two tables to pass to view

I have two tables, "accounts" and "Followups". I want to be able to pull the data through the FollowupController to pass to the view and run through a foreach loop.

for example; I have multiple rows of accounts in the accounts table that only certain rows will have a followup linked to it through a foreign key. I want to be able to iterate through those follow ups. Pulling the data from the follow ups table is easy. But I'm not sure how to pull data from the accounts table in the same foreach loop.

This is what I have so far (obviously not working);

View:

@foreach($accounts as $account)
  {{$account->sName}}
  @foreach($followups as $followup)
    <div style="padding-bottom: 5px">
      <h5>{{$followup->followSubject}}</h5>
      <p><b>Date Created: </b> {{$followup->followCreateDate}}</p>
      <p><b>Follow Up By: </b> {{$followup->followUpEndDate}}</p>
      <p>{{$followup->followNotes}}</p>

    </div>
  @endforeach

@endforeach

Controller:

    public function index()
{
    $followups = Followup::all();
    $accounts = Account::all();
    return view('followups')->with('followups', $followups)
    ->with('accounts', Account::all());
}

Model for Accounts:

function followups() {
    return $this->hasMany(Followups::class);
}

Model for Follow ups:

public function account() {
    return $this->belongsTo('App\Account');
}

Thanks in advance.

Upvotes: 0

Views: 518

Answers (1)

Leo
Leo

Reputation: 7420

Just eagerload them, those that have a follow up will be displayed:

public function index()
{ 
    $accounts = Account::with('followups')->get();
    return view('followups', ['accounts'=>$accounts]);
}

Then access them on the blade:

  @foreach($accounts as $account)
         {{$account->followups->attribute}}
  @endforeach

For more check Laravel eageloading

Upvotes: 1

Related Questions