I have three tables:
Products
id
- other values
Downloads
id
user_id
product_id
Users
id
name
I’d like to fetch last X Download table rows, get their product_id & user_id, product_id match Product table as user_id match User table, then make
foreach ($values as $value) {
<div class="product_title"> {{$product->name}} </div>
<div class="who_downloaded"> {{$user->name}} </div>
}
I can pass in my controller Download model, but it doesn’t get me anywhere close
public function index() {
return view('nav/index', [
'trendings' => Template::orderBy('views', 'DESC')->where('is_active', 'yes')->take(8)->get(),
'latests_downloads' => Downloads::orderBy('id', 'DESC')->take(8)->get(),
]);
}
'latests_downloads' => Downloads::orderBy('id', 'DESC')->take(8)->get()
function just gives me:
id | user_id | product_id |
---|---|---|
1 | 7 | 10 |
2 | 9 | 2 |
3 | 45 | 86 |
4 | 88 | 85 |
5 | 5 | 2 |
6 | 7 | 7 |
7 | 5 | 5 |
8 | 9 | 6 |
But how can I take these values and put in view?
2
Answers
Download
model class (If they don’t already exist.)Yes for this type of scenario you need to use a relationship-based Eloquent model query of Laravel and it is very powerful for this type of scenario.
First You need to add two relationships in the Download model :
And rest of the things work well with this single query.
// user this query
instead of => getting two different queries in two different variables.
You only need to get a single collection of records in a minimum query and a minimum number of variables. You can do it with Eloquent easily.
And last you can use inside blade as like normal we use daily.