【问题标题】:laravel request is undefinedlaravel 请求未定义
【发布时间】:2017-03-16 00:15:00
【问题描述】:

我是 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();

我可以 echo $customer_id 出来,但是在这个 eloquent 中没有定义

【问题讨论】:

  • $request->get("key"); 怎么样?
  • 检查我的更新以修复您的错误。您需要添加use($customer_id)
  • 如果我 dd($request->get('key') 我得到了值。我不知道为什么如果分配给 var 它不起作用。
  • 只需检查我的更新以获取修复。

标签: angularjs laravel request http-post


【解决方案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);
}]);

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

【讨论】:

  • 我输入了@EddyTheDove
  • 即使使用全局助手?请将您的控制器添加到您的问题中,让我们看看。
猜你喜欢
  • 2019-08-10
  • 2017-02-01
  • 2016-09-04
  • 2019-02-18
  • 2015-08-15
  • 2019-10-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多