从路由更新响应数据


Update response data from a route

我有一个路由:

 .../first

下面的函数:

function first() {
   $data['first'] = 1;
   return response()->json($data);
} 

Then I'm working on new route:

.../second

这叫:

function second() {
   ...
   if ($condition) {
      return redirect()->to('.../first');
   }
}

这是return:

{
  "first": 1
}

我想有一个结果,当我调用第二个()函数,看起来像:

{
  "first": 1,
  "second" : 2
}

我怎么能做到这一点,我试图把关键的second响应从重定向()(Cannot use object of type Illuminate'Http'RedirectResponse as array),以及检查条件:

function first() {
   $data['first'] = 1;
   if (Request::is('.../second') { 
      $data['second'] = 2; // but this never execute,request now is ".../first"
   }
   return response()->json($data);
} 
有谁能帮我吗?谢谢阅读

如果first()second()在同一个控制器中,可以在类定义中声明data

class ...
{
    var $data;
    function first() {
        $this->data['first'] = 1;
        return response()->json($this->data);
    }
    function second() {
        if ($condition) {
            $this->data['second'] = 2;
            return $this->first(); // No redirect
        }
        ...
    }

如果上述解决方案无论如何都不可行,请在路由定义中为first()保留一个可选参数。

Route::get('/first/{data?}', 'SomeController@first')->name('first');

Ref - https://laravel.com/docs/5.2/routing#route-parameters

然后,您可以使用second()函数中的数据重定向到first()

function second() {
    if ($condition) {
        return redirect()->route('first', ['data' => ['second' => 2]]);
    }
    ...
}

现在,接收到的参数可以很容易地合并到您的first()函数中。

function first($data = []) {
    $data['first'] = 1;
    return response()->json($data);
}