PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, February 3, 2022

[FIXED] Laravel Best Practice: Print Json response

 February 03, 2022     laravel, laravel-5, laravel-5.5     No comments   

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
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing