laravel请求未定义

时间:2017-03-16 00:15:01

标签: angularjs laravel request http-post

我是Laravel的新手,所以一切都在探索期。我使用angular http post将数据发送到laravel并且在laravel控制器中我能够

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')

我得到$ request是未定义的。请指教!!!

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);
        }
    }
GospelController.php第60行中的

ErrorException: 未定义的变量:customer_id

我认为问题是

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

我可以回复$ customer_id,但是在这个雄辩中没有定义

1 个答案:

答案 0 :(得分: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);
}]);

发生错误是因为你在一个闭包内,并且它无法访问外部变量。