2017-03-16 97 views
2

我是Laravel的新手,所以一切都處於探索期。我使用的角度HTTP POST到到laravel和laravel控制器發送數據我能夠laravel請求是undefined

dd($request) 

Request {#40 
    #json: ParameterBag {#32 
    #parameters: array:4 [ 
     "GPTour_id" => 1 
     "customer_id" => 1 
     "status" => "Confirmed" 
     "note" => "asdfasdf" 
    ] 
    } 
    #userResolver: Closure {#300 
    class: "Illuminate\Auth\AuthServiceProvider" 
    this: AuthServiceProvider {#22 …} 
    use: array:1 [ 
     "$app" => Application {#3 
     #basePath: "/Users/haophung/Dropbox/server/websites/nglaravelyep/laravel-backend" 
     #hasBeenBootstrapped: true 
     #booted: true 
     #bootingCallbacks: [] 

但是,如果我使用

$request->input('key') 

我得到$請求是不確定的。請指教!!!

public function addGospelCustomer(Request $request) 
    { 
     if ($request) { 
      $customer_id = $request->get('customer_id'); 
      $tour_id = $request->get('GPTour_id'); 
      $validator = Validator::make($request->all(), [ 
       'customer_id' =>'required' 
      ]); 

      if ($validator->fails()) { 
       return response()->json(['error' => $validator->errors()], 406); 
      } 
      $gospel_customer = Gospel_tour::find($tour_id)->with(['customers' => function($query) { 
       $query->where('id', $customer_id); 
      }])->first(); 

      if ($gospel_customer === 'null') { 
       return response()->json(['error' => "The Customer is already on the list"], 406); 
      } 

      return 'success';//response()->json(['success' => $request], 200); 
     }else { 
      return response()->json(['error' =>'can not add customer'], 401); 
     } 
    } 

ErrorException在GospelController.php線60: 未定義的變量:CUSTOMER_ID

我認爲這個問題是

$gospel_customer = Gospel_tour::find($tour_id)->with(['customers' => function($query) { 
     $query->where('id', $customer_id); 
    }])->first(); 

我可以回聲$ CUSTOMER_ID出來,但在這個雄辯沒有定義

+0

'$ request-> get(「key」);' 怎麼樣? –

+0

檢查我的更新以解決您的錯誤。你需要添加use($ customer_id)' – EddyTheDove

+0

如果我dd($ request-> get('key')我得到了值。我不知道爲什麼分配給var它不起作用。 –

回答

1

你需要在你的函數定義中輸入提示

public function name(Request $request) {} 

而且使用它像

$key = $request->key; 
$key = $request->get('key'); 

或者使用全局函數

$key = request('key'); 

更新

如果你有錯誤異常做

$gospel_customer = Gospel_tour::find($tour_id)->with(['customers' => function($query) use ($customer_id) { 
    $query->where('id', $customer_id); 
}]); 

發生該錯誤是因爲您處於閉包內部,並且無法訪問外部變量。

+0

我做過打字@EddyTheDove –

+0

但它仍然不起作用嗎? – EddyTheDove

+0

不能正常工作@EddyTheDove –