lundi 29 juin 2020

Laravel best strategy to serve requests from API and form at the same time

Using Laravel 7.*, I'm tasked with creating a simple app to send requests for payment, the user fill a form and send the data then I validate the user inputs and create a new Payment instance.

Then the user is redirected back to the same page. (Of course there are other requests for listing all payments and updating a payment):

   //In PaymentController.php

   public function store()
    {
        $inputData = $this->validateRequest();

        $person = $this->personRepository->findOneByAttribute('id_number', request('id_number'));

        if ($person instanceof Person) {
            $this->paymentRepository->create($inputData, $person);
            return back()->with('successMessage', 'Your payment request registered successfully.');
        } else {
            return back()->with('failureMessage', 'Shoot! Cannot find a peron with the given Identification Number.')->withInput();
        }
    }

Everything is fine, but I need to implement a Restful API to do the same request and get a valid json response, Assuming there is no front-end JavaScript framework, what is the best approach to achieve this goal?

Should I create a separate controller? Or Simply check whether request is sent from a traditional form or an API client? Am I missing a design pattern?

Aucun commentaire:

Enregistrer un commentaire