Search code examples
phplaravelpackagelaravel-5.1laravel-routing

How do I pass a parameter to a controller action within a Laravel Package?


Within a Laravel package I made, I want to redirect the user to a controller action that requires a parameter (within the same package).

Controller:

public function postMatchItem(Request $request, $id)
{
    $this->validate($request, [
        'item_match' => 'required|numeric|exists:item,id',
    ]);

    $spot_buy_item = SpotBuyItem::find($id);

    $item = Item::find($request->input('item_match'));

    $price = $item->getPrice();

    $spot_buy_item_response = new SpotBuyItemResponse();
    $spot_buy_item_response->spot_buy_item_id = $id;
    $spot_buy_item_response->spot_buy_id = $spot_buy_item->spot_buy_id;
    $spot_buy_item_response->item_id = $item->id;
    $spot_buy_item_response->user_id = $spot_buy_item->user_id;
    $spot_buy_item_response->spot_buy_price = $price;
    $spot_buy_item_response->created_ts = Carbon::now();
    $spot_buy_item_response->save();

    return redirect()->action('Ariel\SpotBuy\Http\Controllers\Admin\SpotBuyController@getPart', [$id]);
}

The action in the redirect is the same path I use in my routes.php file to direct the user to this controller action

Route:

Route::get('/part/{id}', 'Ariel\SpotBuy\Http\Controllers\Admin\SpotBuyController@getPart')->where('id', '[0-9]+');

I've tried variations of this path without success, including SpotBuyController@getPart like the documentation suggests (https://laravel.com/docs/5.1/responses#redirects)

Note: I got this to work by naming my route in routes.php and using return redirect()->route('route_name', [$id]);, but I still want to know how to pass a package controller action to the ->action() function.


Solution

  • It's trying to access your controller from within the App\Http\Controllers namespace. Can see they've added it to your controller name in your error:

    App\Http\Controllers\Ariel\SpotBuy\Http\Controllers\Admin\SpotBuyController@getP‌​art

    You need to escape the Ariel namespace with a \ at the start:

    return redirect()->action('\Ariel\SpotBuy\Http\Controllers\Admin\SpotBuyController@getPart', [$id]);