Reputation: 887
I've setup a few model relationships and I'm trying to feed that data to a page that's displays a table with different columns to show the information. I've seeded 3 Tables (customers, jobs, steps) with Faker dummy data just for testing. How can I pull in the "Steps" table column data? My controller defines both (2) variables for the Job & Step model but I'm unsure how to pull in Step to the display. Do I have to do an array for the the variables called in the controller?
Here's my controller setup
public function index()
{
$jobs = Job::all();
$steps = Step::all();
return view('jobs.home', compact ('jobs', 'steps'));
}
Here's my blade setup
@foreach ($jobs as $job)
<tr>
<td>{{ $job->number }}</td>
<td>{{ $job->customer->name }}</td>
<td>NEED TO ADD STEPS COLUMN Here</td>
</tr>
@endforeach
Upvotes: 1
Views: 274
Reputation: 3323
There are several ways that this could be done, depending on what kind of data your "Step" model is providing for you.
If you just need 1 item from the "Step" model, you could first find just the specific data you need from the "Step" model instead of pulling in everything with Step::all();
for instance, you could use one of the more specific methods under "Collection Methods" that just return one item: https://github.com/susanBuck/notes/blob/master/05_Laravel/11_Databases_Eloquent_Collections.md
If you need more than 1 item, then you can use a more specific Collection method as well; however, you are going to have to loop through it to extract out each individual item. You will have to use "if" statements to determine which item is the one you want and then pull in its column data the same way you did with the "jobs" item like $job->number
.
For your second question, you don't have to use an array to return the items from the controller. Just get the value you want there and return that if you like. For instance, to get the first "step" (if you just wanted the first one) then in the Controller do this to return a variable instead of an array:
public function index()
{
$firstStep = Step::first();
return view('jobs.home')->with('firstStep', $firstStep);
}
and then in your Blade file, you can access the data column rows just like you did with your $job variable:
{{ $firstStep->someColumn}}
Upvotes: 1