【问题标题】:Inertiajs - Laravel: How to Throw custom ErrorInertiajs - Laravel:如何抛出自定义错误
【发布时间】:2021-11-02 23:56:47
【问题描述】:

如何在不重定向的情况下在 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)
                }
            });

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!'
            ]);
        }

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

非常感谢。

【问题讨论】:

    标签: laravel vue.js inertiajs


    【解决方案1】:

    试试这个:

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

    应该收到错误onError

    onError: (errors) => {
       window.Toast.error(errors.create)
    }
    

    【讨论】:

    • 非常感谢!所以我希望现在我有一切可以替换 Axios 请求 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-19
    • 2014-09-21
    • 1970-01-01
    • 2013-01-15
    • 1970-01-01
    • 2020-10-23
    相关资源
    最近更新 更多