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

Wednesday, January 19, 2022

[FIXED] How to change response in Laravel?

 January 19, 2022     laravel, laravel-5, laravel-5.4, laravel-response     No comments   

Issue

I have RESTful service that is available by endpoints.

For example, I request api/main and get JSON data from server.

For response I use:

return response()->json(["categories" => $categories]);

How to control format of response passing parameter in URL?

As sample I need this: api/main?format=json|html that it will work for each response in controllers.


Solution

You can use for this Response macros. For example in AppServiceProvider inside boot method you can add:

\Response::macro('custom', function($view, $data) {
    if (\Request::input('format') == 'json') {
            return response()->json($data);
    }
    return view($view, $data);
});

and in your controller you can use now:

$data = [
   'key' => 'value',
];

return response()->custom('your.view', $data);

If you run now for example GET /categories you will get normal HTML page, but if you run GET /categories?format=json you will get Json response. However depending on your needs you might need to customize it much more to handle for example also redirects.



Answered By - Marcin NabiaƂek
  • 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