A
A
Artem00712018-04-13 20:40:47
Laravel
Artem0071, 2018-04-13 20:40:47

How to display info at the end of the controller?

Making an API for the front
Created a trait so that all outputs have the same format:

namespace App\Traits;


trait Output
{
    protected $success = true;
    protected $statusCode = 200;
    protected $errors = [];
    protected $data = [];

    public function setData(array $data = [])
    {
        $this->data = array_merge($this->data, $data);

        return $this;
    }

    ...

    public function renderOutput()
    {
        return response()->json([
            'success' => $this->success,
            'code' => $this->statusCode,
            'errors' => $this->errors,
            'data' => $this->data
        ], $this->statusCode);
    }

Connected it in the global controller:
class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests, Output;
}

Now I can do something like this in any controller: But at the end of all controllers I have only one line: Can I write something in the global controller to get rid of this line in other controllers? ps, I understand that there is nothing complicated in writing one line, but I'm still wondering if there is a solution for this task
$this->setData(['user' => $user]);
return $this->renderOutput();

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Konstantin Tolmachev, 2018-04-14
@dark_tke

As an example that immediately comes to mind, you can use __destruct()
It is always executed at the end of the controller, and can output the necessary information

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question