rome 웃 rome 웃 - 3 months ago 22
PHP Question

Update response data from a route

I have a route:

.../first


this call below function:

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


Then I'm working on new route:

.../second


this call:

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


this is return:

{
"first": 1
}


I want to have a result, when I call second() function, look like:

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


How can I do that, I'm trying to put the key
second
to response from redirect() (
Cannot use object of type Illuminate\Http\RedirectResponse as array
)
, as well as check condition :

function first() {
$data['first'] = 1;
if (Request::is('.../second') {
$data['second'] = 2; // but this never execute,request now is ".../first"
}
return response()->json($data);
}


Can anyone help me out? Thanks for reading.

Answer

If first() and second() are in same controller, you could declare data in a class definition.

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
        }
        ...
    }

If solution above is not feasible anyhow, keep an optional parameter for first() in your route definition.

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

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

Then, you could redirect to first() with data from your second() function.

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

Now, received parameter can be merged in your first() function easily.

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