Home > Net >  Stumpped trying to pass two parameters from view form to controller
Stumpped trying to pass two parameters from view form to controller

Time:11-08

I have a Laravel 6 app and am trying to pass two parameters from my view's form to my controller via a resource route. I can pass one, no problem, but passing two gives the same error:

Too few arguments to function App\Http\Controllers\Admin\SubscriptionsController::update(), 1 passed and exactly 2 expected

I've tried many different arrangements suggested from other posts but none bring the desired result.

Here's my route:

Route::resource('subscriptions', 'Admin\SubscriptionsController')

Here's my form in my view:

 {{ Form::open(['route' => ['admin.subscriptions.update', $plan->id, $coupon_code], 'method' => 'PUT', 'id' => 'role-' . $plan->id, $coupon_code]) }}
                                            Coupon Code: <input type="text" name="coupon_code">
{{ Form::close() }}

Here's my controller. It doesn't reach the dd() test.

public function update($id, $coupon_code)
    {
        dd($coupon_code);
...

In the error Whoops! page, I can see the POST DATA that $coupon_code is being sent over.

screenshot of POST_DATA

However, if I remove the $coupon_code parameter from the controller (leaving public function update($id) ) it functions fine passing $id from form to controller, but I don't get the $coupon_code data I need to process. Adding the second parameter bombs it.

Any suggestions are very welcome.

CodePudding user response:

As you are using the resource controller, it won't allow you to pass additional fields directly to its update() route. Instead, you have to override the update route.

Here is how you can do it, Immediately below your resource.

You can add a new route as below:

// web.php
Route::resource('subscriptions', 'Admin\SubscriptionsController')

// Make sure you add name when you are overriding the route
Route::put('subscriptions/{subscription}/{coupon_code?}', 'Admin\SubscriptionsController@update'])->name('admin.subscriptions.update');

I believe you won't be sending the coupon code every time so you can add {coupon_code?} which becomes optional.

In you controller's update() method, make the coupon_code optional

public function update($id, $coupon_code = null)
{
  ...
}

CodePudding user response:

You can not add a new param for Route::resource. If you really want to take 2 params, you should create a new route.

for an example:

    Route::resource('subscriptions', 'Admin\SubscriptionsController')->except('update');
    Route::put('/subscriptions/{id}/{coupon_code}', 'Admin\SubscriptionsController@update')->name('subscriptions.update');

But I think it's better not using method params. Why not just using input form?

so we can process the coupon code like this:

request()->coupon_code;
  • Related