Reputation: 1325
I'm putting together a simple shopping cart system, using Laravel and Vue.js, to sell photos. Each photo comes in a range of sizes, with the price of each size being different.
I have the following tables:
Photos
- id
- title
Sizes
- id
- dimensions
Photos_Sizes
- id
- photo_id
- size_id
- price
I'm using Vue.js to make API calls to my cart controller to manipulate the cart. It passes the photo_id and size_id when the user clicks the Add to Basket button. Naturally I want to grab the price of a selected item from the database rather than client side to prevent any cheekiness, and that naturally means querying the pivot table.
My question is, using the two ids passed to the controller, how can I access the correct price value in the pivot table?
Upvotes: 0
Views: 320
Reputation: 365
On the relationships for both Photos and Sizes, add ->withPivot('price')
Then once you have your result set, you can access the field with $size->pivot->price
Upvotes: 0
Reputation: 30154
You can use Query Builder in your controller like this:
public function price(Request $request)
{
$row = DB::table('Photos_Sizes')
->where('photo_id', $request->input('photo_id'))
->where('size_id', $request->input('size_id'))
->first();
return Response::create($row->price, 200);
}
Upvotes: 1