Inertiajs - Laravel:如何抛出自定义错误
Inertiajs - Laravel: How to Throw custom Error
如何在 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)
}
});
Laravel控制器():
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 组件中抛出一个错误。
非常感谢。
试试这个:
try {
// ...
} catch(Excpetion) {
return redirect()->back()->withErrors([
'create' => 'ups, there was an error'
])
}
应该收到错误 onError
onError: (errors) => {
window.Toast.error(errors.create)
}
如何在 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)
}
});
Laravel控制器():
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 组件中抛出一个错误。
非常感谢。
试试这个:
try {
// ...
} catch(Excpetion) {
return redirect()->back()->withErrors([
'create' => 'ups, there was an error'
])
}
应该收到错误 onError
onError: (errors) => {
window.Toast.error(errors.create)
}