1

For some reasons I send JSON response from my helper/library instead of controller using below code:

response()->json(
    [
        "status"  => false,
        "message" => "This product is out of stock",
    ],
    200
)->send();
exit;

my problem is no middleware header if that response sent. How to attach header to all response()->json()->send();exit; function?

Below us my response header of default controller ): enter image description here

Above response has all header from all middleware and below is my header response from response()->json()->send();exit;:

enter image description here

above not showing headers from the middleware.

I know I can send the header manually by add ->header('X-Header-One', 'Header Value') like code below:

response()->json(
                [
                    'status'  => false,
                    'message' => 'This voucher is not for selected products',
                ]
            )->header('X-Header-One', 'Header Value')->send();
            exit;

But I already have so many that responses, and I dont want to try to WETing my code.

2
  • why don't you create a middleware and apply there? Commented Oct 26, 2020 at 4:02
  • Middleware is not working on that , see my screenshot above Commented Oct 26, 2020 at 4:07

4 Answers 4

2

After doing some digging, you could also create a Response Macro

https://laravel.com/docs/8.x/responses#response-macros

<?php

namespace App\Providers;

use Illuminate\Support\Facades\Response;
use Illuminate\Support\ServiceProvider;

class ResponseMacroServiceProvider extends ServiceProvider
{
    /**
     * Register the application's response macros.
     *
     * @return void
     */
    public function boot()
    {
        Response::macro('custom', function ($value) {
            return Response::json($value)->headers();
        });
    }
}

Then in your code, just use

return response()->custom($data);
Sign up to request clarification or add additional context in comments.

Comments

1

Create a middleware SetHeader.php

then

<?php

namespace App\Http\Middleware;

use Closure;

class setHeader
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $request->headers->set('X-Header-One', 'Header Value');
        return $next($request);
    }
}

like that you can add as may as headers and apply to those routes which you want to send

8 Comments

Middleware is not working on that response, that's why asked, if it worked like in controller the problem is solved
it should work as i m using same and for me it is working
No, maybe you use return response() not like me without return but put exit/die after that response()->json()->send();exit;,
try my code in your model or helper or library and you know what I mean
i think my code is set header to request and your code is set headers to response becouse your checking headers which are come back from server and my code is while sending req. to server we modify the headers then it goes to controller with new headers
|
1

Well, the answer to this question is already given, But I suggest using the power of the middleware concept. Middleware is not just working for requests but also works for the response.

By using the response macro we have to change the reference to use a custom function instead of json.

Here is the middleware code.

SetResponseHeaders.php

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class SetResponseHeaders
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        $response = $next($request);
        $response->header('X-Header-One', 'XValue');
        return $response;
    }
}

and don't forget to register the middleware.

Http/Kernel.php

protected $middleware = [
    // other middlewares
    \App\Http\Middleware\SetResponseHeaders::class,
]

Special notes:- If you are using the CORS concept then you have the cors.php file under the config folder. In my case, I am using fruitcake/laravel-cors package. so you have to expose the header otherwise you will not get the value.

cors.php

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Cross-Origin Resource Sharing (CORS) Configuration
    |--------------------------------------------------------------------------
    |
    | Here you may configure your settings for cross-origin resource sharing
    | or "CORS". This determines what cross-origin operations may execute
    | in web browsers. You are free to adjust these settings as needed.
    |
    | To learn more: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
    |
    */

    // other config

    'exposed_headers' => ['X-Header-One'],
]

Comments

0

In your Controller.php

Add a function and call it whatever you want

EG

public function MyCustomResponse()
{
  ... 
}

Then allow that to take in the params you want, in your case it is an array and an int, (data and status)

public function MyCustomResponse(array $data, int $status)
{
  ... 
}

Then handle the logic in there

public function MyCustomResponse(array $data, int $status)
{
  response()->json($data, $status)->header('X-Header-One', 'Header Value')->send();
}

Now when you want to use it, ensure that you are extending the controller where you have placed this code and just do

return $this->myCustomResponse($data, 200);

A better option depending on your need is to use a middleware

public function handle($request, Closure $next)
{
    $request->headers->set( ... );
    return $next($request);
}

And apply to your route

1 Comment

thanks, it's nice idea, but I will try to wait for other idea first.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.