laravellumenlumen-5.4

How to add custom method to Lumen's response class


I'm using response method withHeaders():

return response(view('pages.top.index', compact('data')))->withHeaders(['one-param' => 'data', 'second-param' => 'data2' ...);

And I have multiple same params that I put in withHeaders() method almost in every Controller's action. Is there a way I can add my own method and chain it like:

return response(view('pages.top.index', compact('data')))->customMethod('data', 'data2', ....);

Solution

  • Response is macroable so you can add this to the service provider:

    \Illuminate\Http\Response::macro('customMethod', function () { 
          //Method body
          return $this; //To chain it
    }); 
    

    Note: I tend to avoid this because it gives my IDE a very hard time with type-hinting .

    If the problem is with needing to pass the same data over and over again you might also consider sharing data with all views