Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ChrisSFR's avatar

Restful Api Call Validation and Response

Hi Laracasts community, Recently I'm trying to build a Restful API for my Controller store() method. Other websites are supposed to store objects by passing some parameters via curl. For the Validation I use a Custom FormRequest class. My Problem is, that the FormRequest class redirects if validation fails or is sending a json 422 status code response if the request was ajax. In my case it should send a 422 status code. But it redirects because of FormRequests response error method:

        if ($this->ajax())
        {
            return new JsonResponse($errors, 422);
        }
        else
        {
            return $this->redirector->to($this->getRedirectUrl())
                                            ->withInput($this->except($this->dontFlash))
                                            ->withErrors($errors);
        }

What would be a good approach to implement a validation for my case. Should I override the response error method of FormRequest and add an additional else if for my case? Or is FormRequest unsuitable for my problem and i should go for a custom validation in my store method? Or should curl mimic the ajax requests with X-Requested-With: XMLHttpRequest

Greetings Krizz

0 likes
3 replies
webkenny's avatar
Level 2

Bypass that class altogether. You should instead extend Validator which won't tie you to the behavior of the FormRequest class. I've included a recent example of something I've been working on that might help. Note it uses the validator class I talked about. Also I created an API controller which this one extends that adds a few helper methods. I've included those below as well:

// API Controller
    /**
     * Handles an error response formatting it according to our spec.
     *
     * @param array $error
     * @param array $headers
     * @return \Symfony\Component\HttpFoundation\Response
     */
    protected function respondWithError($error, $headers = [])
    {
        return response()->json(['errors' => $error])->setStatusCode($this->getStatusCode());
    }


    /**
     * @param Model $item
     * @param TransformerAbstract $transformer
     * @return \Symfony\Component\HttpFoundation\Response
     */
    protected function respondWithItem(Model $item, TransformerAbstract $transformer)
    {
        $resource = new Item($item, $transformer);
        return response()->json($this->manager->createData($resource)->toArray())->setStatusCode($this->getStatusCode());
    }
// ModelController

 /**
     * Store a newly created resource in storage.
     *
     * @param  Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $data = $request->input('data');
        $validator = $this->validator($data);

        if ($validator->fails()) {
            $this->setStatusCode(422);
            return $this->respondWithError($validator->errors());
        }

        $account = new Account();
        $account->name = $data['name'];
        $account->subdomain = $data['subdomain'];
        $account->save();

        $this->setStatusCode(201);
        return $this->respondWithItem($account, new AccountTransformer);
    }

    private function validator($data)
    {
        return Validator::make($data, [
          'subdomain' => 'required|unique:accounts|max:50',
          'name' => 'required',
          'address' => 'required|array|min:1',
          'phone' => 'required|array|min:1'
        ]);
    }
3 likes
ChrisSFR's avatar

Thanks for your response. Ok creating an ApiController with response Methods and extending from it seems to be the right way to go. Also thanks for your snippet. Didn't know Http Status Code 201 (created) before. Always used 200 ;)

Please or to participate in this conversation.