So I am quite new to Laravel, and I have a situation, where I am trying to gather data from a pivot table (contains 2 foreign keys only) in order to retrieve data from other tables.
Before everything, I'd like to note, that word "campaign" is the same as "box". Simply it differs in database and front.
I have multiple boxes, that contains specific gifts.
I have set the URL of the box to be something as such: http://127.0.0.1:8000/box/1
http://127.0.0.1:8000/box/2
etc..
I have done so, by simply using a button with the {id}:
<a href="box/{{$item->id}}" class="btn btn-dang btn-xs">View the box</a>
My plan is, to print out only that specific boxes gifts (right now, all boxes print out all gifts).
I have tried to use the ->where option within my function, although, it seems that I can't try equaling to the campaigns ID.
Incorrect code:
function box(){
$data = array(
'list'=>DB::table('campaigns_gifts')
->join('gift_items', 'gift_items.id', '=', 'campaigns_gifts.gift_foreignK')
->select('gift_items.*')
->where($campaign_foreignK = '{id}')
->get()
);
return view('DBqueries.boxView', $data);
}
My question is, how can I specifically return data, that only belongs to that specific box, since I am not able to use mysql where option.
For reference, these are the database tables:
Basically, I would need to match my URL's id with campaign_foreignK
Thank you in advance.
My Answer:
You can achieve this by passing the box ID as a parameter to your controller function and then using that parameter to filter the data in your query. Here's how you can modify your code to achieve this:
1. Update your route to pass the box ID as a parameter:
php
Route::get('/box/{id}', 'BoxController@box');
2. Modify your controller function to accept the box ID parameter and use it in your query:
php
use Illuminate\Support\Facades\DB;
public function box($id){
$data = array(
'list'=>DB::table('campaigns_gifts')
->join('gift_items', 'gift_items.id', '=', 'campaigns_gifts.gift_foreignK')
->select('gift_items.*')
->where('campaign_foreignK', $id)
->get()
);
return view('DBqueries.boxView', $data);
}
With this code, when you visit a URL like http://127.0.0.1:8000/box/1, it will pass the ID 1 to your controller function. The query will then filter the data based on this ID and return only the gifts that belong to that specific box.
Make sure to adjust the column names and table names in the query according to your database structure.
Rate this post
5 of 5 based on 6984 votesComments