1

In laravel8/inertia/vue3 app creating model I set mode of the form in “add” mode and I try when new model is created return it in responce , like :

$role = Role::create([ 'name' => $request->name, 'guard_name' => 'web', ]);

return back ()->with('data', [
    'role' => $role,
]);

But I can not get this new model on client part with code :

this.form.post(this.route('admin.roles.store'), {
    preserveScroll: true,
    onSuccess: (resp) => {
        console.log('resp::')
        console.log(resp)
        Toast.fire({
            icon: 'success',
            title: 'New role created!'
        })
    },

In browser I do not see model returned from control : https://prnt.sc/1xxhS-EOHLSh

How can I do this ?

Thanks!

1 Answer 1

2

I think you misunderstood some things:

First: When you use ->with, you're putting that data in a session flash. You're not returning it to the client. And putting the result into the flash probably isn't what you want.

return back ()->with('data', [
    'role' => $role
]);

Second: If you intend to use onSuccess on the client side to deal with the response, you can't return back(). You need to send an actual response to the client in a traditional AJAX way like this:

return [
   'data' => $role
];

Third: I would encourage you to avoid using onSuccess and returning JSON like described above, since this kind of defeats the purpose of Inertia and I believe it's provided more like an escape hatch for situations where you can't do things "the Inertia way".

Sign up to request clarification or add additional context in comments.

3 Comments

What can be "the Inertia way" here without onSuccess ?
If you stay on the same page, just "return back();". Otherwise redirect to another page which will take care of showing the roles... If you want to do something like toast notifications, you can "return back()->with('toast', 'Message here')" and then handle the toast in the session on the HandleInertiaRequest middleware.
Thanks! it helped, but how can I with message to send also message_type(success/failure) ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.