-1

I am trying to create an error message using a validator. Currently I got it working it using the following code.

        $validator = Validator::make(request()->all() ,[
            'banner' => 'max:2048',
        ], [
            'banner.max' => 'The :attribute must be less than 2MB.',
        ]);

        if ($validator->fails()) {
            return redirect()
                    ->back()
                    ->withErrors($validator)
                    ->withInput();
        }

I don't need to redirect the user when the validation fails. So I have removed the redirect response however, doing so cause me to receive this error with my following code changes. I am not sure why only JSON response is received.

All Inertia requests must receive a valid Inertia response, however a plain JSON response was received

        if ($validator->fails()) {
            return $validator->errors()->all();
        }
Lim Han Yang
  • 350
  • 6
  • 23

1 Answers1

0

The error message you are receiving indicates that you are returning a plain JSON response instead of a valid Inertia response. Inertia is a library that allows you to build single-page applications using server-side routing and client-side rendering. Inertia responses contain both the data and the view components needed to render the page on the client-side.

To return a valid Inertia response, you can use the Inertia::render method to render the appropriate view component with the necessary data. Here's an example of how you can modify your code to return a valid Inertia response:


if ($validator->fails()) {
    return Inertia::render('YourComponent', [
        'errors' => $validator->errors()->all(),
    ])->toResponse(request()); 
}

In this example, YourComponent is the name of the Inertia component that you want to render, and errors is an array containing the validation errors. The toResponse method is used to convert the Inertia response to a standard HTTP response that can be sent back to the client.

Be sure to replace YourComponent with the actual name of your Inertia component.

  • is there a command for me do render the current page I am. I plan to have this validator run across multiple different pages so I will this be on many components. – Lim Han Yang Jun 29 '23 at 04:15
  • 2
    This answer looks like ChatGPT – DavidW Jun 29 '23 at 09:26
  • 1
    @LimHanYang, do you mean artisan command? – javierstere Jun 29 '23 at 12:47
  • @javierstere no I mean is there any inertia response I can use, which doesn't required to redirect to a component? I would like to create a response that keep me on the same page no matter where I am. – Lim Han Yang Jun 29 '23 at 13:42