9

How isit possible to throw an custom Error from Laravel in Inertiajs.vue without redirecting then?

Vue Component:

Inertia.post('company-organisations-create', {
                name: this.newOrganisation.name, 
                description: this.newOrganisation.description
            }, 
            {
                preserveScroll: true,
                onSuccess: (page) => {
                    return Promise.all([
                        window.Toast.success(this.$page.props.toast.message),
                        this.newOrganisation.name = '',
                        this.newOrganisation.description = '',
                    ])
                },
                onError: (errors) => {
                    window.Toast.error(errors.toastMessage)
                }
            });

LaravelController():

    public function createOrganisations(Request $request)
        {
          try {
    
            CompanyOrganisations::create([
                'company_id' => $companyID,
                'name' => $orgName,
                'description' => $orgDescription,
            ]);
           } catch(Excpetion) {
               // Create Inertia Error 'onError'
               /* As example with json response
                  return response()->json([
                     'message' => 'ups, there was an error',
                  ], 403);   */
           }       
    
            return Redirect::route('company.organisations',
            )->with([
                'toastMessage' => 'Organization created!'
            ]);
        }

As Im not able to receive json format in Inertia request, I need to throw a error in Inertiajs.vue Component.

Thank you very much.

Carlson
  • 183
  • 2
  • 11

1 Answers1

15

Try this:

try {
// ...
} catch(Excpetion) {
   return redirect()->back()->withErrors([
      'create' => 'ups, there was an error'
   ])
}           

The errors should be received onError

onError: (errors) => {
   window.Toast.error(errors.create)
}
Matheus Dal'Pizzol
  • 5,735
  • 3
  • 19
  • 29