Inertiajs - Laravel:如何抛出自定义错误

Car*_*son 9 inertiajs laravel vue.js

如何在 Inertiajs.vue 中从 Laravel 抛出自定义错误而不进行重定向?

Vue 组件:

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)
                }
            });
Run Code Online (Sandbox Code Playgroud)

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!'
            ]);
        }
Run Code Online (Sandbox Code Playgroud)

由于我无法在 Inertia 请求中接收 json 格式,因此我需要在 Inertiajs.vue 组件中抛出错误。

非常感谢。

Mat*_*zol 22

尝试这个:

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

应该收到错误onError

onError: (errors) => {
   window.Toast.error(errors.create)
}
Run Code Online (Sandbox Code Playgroud)