0
votes

I was wondering if there is any way to request through the URL and use an id in a Laravel resource? I explain myself, I am storing price data in a pivot table, and what I want to do is that when entering a route like this: api/{IdFromURL}/products just call the related prices when (inventory_id = IdFromURL)

In my api:

Route::get('{inv}/products','ProductController@city');//im not using this $inv request yet

In my controller:

public function city($inv)//im not using this $inv request yet
    {
       return ProductResource::collection(Product::with('inventories')->paginate(25));

    }

In my resource:

What I am doing here is assigning the price of the product_id obtained from the table, the problem is that it is a many-to-many relationship, so the product can have several prices, so I need to obtain the price obtained from the product and inventory relationship, the id of the inventory is what I need to enter through the url

$data = DB::table('inventory_product')
       ->where('product_id', '=', $this->id)
//THE IDEA:
       ->where('inventory_id', '=', {IdFromURL}) //how do I get that IdFromURL???
       ->first();


return [
           //other staff
           'price'=>$data->price,
        ];

So, what i need is

URL: api/1/products

should show all products with the prices of inventory 1

URL: api/2/products

should show all products with the prices of inventory 2

Is it possible do that how I'm planning? Thank you in advance :)

1

1 Answers

0
votes

If I understand your question correctly, you have the ability to pass multiple url parameters in PHP. In your route you can always pass through additional request params like:

api/1/products?inventory_id=10 // your inventory id

Then in your controller type hint the Illuminate\Http\Request in your store function like:

   public function store(Request $request) {

     dump($request->all()); // This all will hold all your input vars inventory_id.

     // access inventory_id and other params like this:
     $request->input('inventory_id')

   }