Thursday, February 3, 2022

[FIXED] Laravel Best Practice: Print Json response

Issue

I've been wondering what is the best way in Laravel to return a json array back to an ajax call. This is the way I'm working right now:

Route in web.php

Route::group(['prefix' => 'users'], function () {
    Route::post('getOneTimeLink', [
        'as' => 'adminUserOneTimeLink', 
        'uses' => 'AdminUsersController@createOneTimeLink'
    ]);
});

Controller in AdminUsersController.php

public function createOneTimeLink(){
    $aResponse = [ 'someData' => 'someValue'];
    // do some stuff here

    echo json_encode($aResponse);
    die()
}

but I think there is another way to return the call instead of adding the json_encode then die() the execution... but I don't know it yet. I've tried to search but haven't yet found an answer. I hope any of you can help me.

Thank you so much!


Solution

return response()->json($aResponse);

More information: https://laravel.com/docs/5.5/responses#json-responses



Answered By - Paul

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.