J Alcantara J Alcantara - 5 months ago 10
PHP Question

Laravel pass variable from FirstController to SecondController

This is my two routes which pass variable on each view.

Route::resource('product', 'ProductController');
Route::resource('booking', 'BookingController');

I created a view which display the current product (ex. http://localhost:8000/product/15) using the ProductController.

Now i created another view to book this product then insert it (modal pop up) inside the product view using @include('partials.booking').

The problem is how can i pass the product id to the BookingController? It is possible?


This depends a lot on what framework you use in your frontend ( jquery etc. )

Usually your popup should somehow know what product it is referred to. You can do this for example like this

<!-- this is your html / blade -->
<div class="booking-popup">
  <button class="book" data-product="{{$product->id}}">Book Now!</button>

You can then use ajax and jquery for example to get the data attribute

Another option is to provide a form with a hidden field

<form action="/booking" method="post">
   <input type="hidden" name="product_id" value="{{$product->id}}" />
   <input type="submit" value="Book Now!" />

If you use the laravel html collective you can simplify it even more


Since your Bookings actually belong to a product you could also rearrange your resources so that a booking is create with the route

/product/5/booking (POST)

You could then simply access the product id as parameter of the route

EDIT 2 To access it from your controller simply ( case of hidde form input )

public function store(\Illuminate\Http\Request $request) {

If you defined it via route simply go for whatever you set as placeholder

Route::post('product/{product}/book', 'BookingController@store');

Controller then:

public function store(\Illuminate\Http\Request $request, $product) {