在Laravel中使用GET参数发送POST请求

时间:2017-11-10 17:16:47

标签: php laravel post get routes

例如,我在web.php中有这条路线: -

Route::get('products/{product}/owners', 'ProductController@showOwners');

当我尝试添加新的'所有者'对于产品,我必须在父URL中执行此操作,如下所示: -

Route::post('products/storeOwner', 'ProductController@storeOwner');

然后我在表单中的隐藏字段中传递产品ID,因为发布请求不接受URL参数。那么无论如何都要像下面这样做?

Route::post('products/{product}/storeOwner', 'ProductController@storeOwner');

因此,POST请求将在特定的'产品内发送。网址是什么?
更新

/* ProductController Class */
public function storeOwner (AddProductOwner $request)
    {

        $product= Product::find($request->product);
        $user = Auth::user();

        if ( $user->ownerOf($product)) {
            // Check if the current user is already one of the owners).
            // If the current user is the owner then return to the product
            // This line is not executed because in (products/show.blade.php) we have set a condition.

            return redirect('products/' . $request->product);
        }

        $join = new Join;
        $join->role = $request->join_role;
        $join->product()->associate($request->product);
        $join->user()->associate(Auth::user());

        $join->message = $request->message;


        $join->save();

        // TODO: we have to make this with ajax instead of normal form
        return redirect('products/'. $request->product);
}



我希望我的问题很清楚......

2 个答案:

答案 0 :(得分:1)

是的,你可以像你在上一条路线中提到的那样做

Route::post('products/{product}/storeOwner', 'ProductController@storeOwner');

然后在函数参数中获取产品ID

public function storeOwner (AddProductOwner $request, $productId)
{
    dd($productId);    // TRY THIS OUT. CHECK THE 2nd ARGUMENT I SET.
    $product= Product::find($productId);    // PASS THE VERIABLE HERE.
    $user = Auth::user();

    if ( $user->ownerOf($product)) {
        // Check if the current user is already one of the owners).
        // If the current user is the owner then return to the product
        // This line is not executed because in (products/show.blade.php) we have set a condition.

        return redirect('products/' . $request->product);
    }

    $join = new Join;
    $join->role = $request->join_role;
    $join->product()->associate($request->product);
    $join->user()->associate(Auth::user());

    $join->message = $request->message;


    $join->save();

    // TODO: we have to make this with ajax instead of normal form
    return redirect('products/'. $request->product);

}

答案 1 :(得分:1)

您可以将URL参数发送到POST请求。只需确保您在表单中发送通配符。

 <form action="/products/{{ $productid }}/storeOwner" method="POST">

在您的路线中

Route::post('products/{productid}/storeOwner', 'ProductController@storeOwner');

在你的控制器中,使用它

public function storeOwner($productid)
{
    dd($productid);
}