簡體   English   中英

如何將 laravel 中的 post 參數從路由傳遞到控制器?

[英]How to pass post parameters in laravel from the route to the controller?

我正在支付控制器中執行此查詢,我需要從路由中獲取發布請求。

控制器:

class PaymentController extends Controller 
{
    public function apiPaymentByUserId($date_from, $date_to) { 


        $payments = DB::table("casefiles, payments")
            ->select("payments.*")
            ->where("casefiles.id", "=", 'payments.casefile_id')
            ->where("casefiles.user_id", "=", Auth::id())
            ->where("payments.created_at", ">=", $data_from)
            ->where("payments.updated_at", "<=", $data_to)
            ->get();

            
            return response()->json([ 
                'success' => true, 
                'response' => $payments 
            ]);
    
    }
}

路線:

Route::post('/payments/{date_from}/{date_to}', 'Api\PaymentController@apiPaymentByUserId');

如何在這個帖子路由中傳遞多個參數? 謝謝

對於發布請求,無需在 url 中傳遞參數。您將進入請求

所以路線將是

Route::post('/payments', 'Api\PaymentController@apiPaymentByUserId');

和控制器方法

public function apiPaymentByUserId(Request $request) 
{ 
    $date_from = $request->date_from;
    $date_to = $request->date_to;
}

如果您不想更改您的 url,請在您的控制器apiPaymentByUserId()方法中嘗試此操作,注入 Request 對象以及其他路徑變量,例如:

public function apiPaymentByUserId(Illuminate\Http\Request $request, $date_from, $date_to) { 
      // ... you can access the request body with the methods available in $request object depending on your needs.
}

對於POST請求,無需在 url 中傳遞參數 將日期作為通過 POST 方法發送的 FORM 值與其余 FORM 值一起發送(如果有,您已經在 FORM 中發布)。 您將獲得通過請求 $request對象實例中的 POST 方法發送的所有 FORM 值,並在Controller/Method中傳遞。

所以路線將是:

Route::post('/payments', 'Api\PaymentController@apiPaymentByUserId');

和控制器方法:

public function apiPaymentByUserId(Request $request) 
{ 
    $date_from = $request->date_from;
    $date_to = $request->date_to;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM