简体   繁体   中英

Redirect route with data in Laravel Vue Inertia stack

In my controller i have

public function store(Request $request)
    {
        $postData = $this->validate($request, [
            'name' => 'required',
            'status' => 'required | boolean'
        ]);

        Room::create([
            'name' => $postData['name'],
            'active' => $postData['status'],
        ]);

        $message = "Room Added";

        return redirect::route('rooms.index', ['msg' => $message]);
    }

and i used 'msg' in my props

props:['rooms','errors','msg']

But for {{msg}} gives undefined and not any message.

You're passing msg as a param to your route, not as a param to your Inertia::render call. And since you're redirecting, you probably want to flash the message to the session and handle it on the HandleInertiaRequests middleware. Look into the example in the documentation .

So, first you redirect to rooms.index flashing the message:

return redirect()->route('rooms.index')->with('message', 'My message');

Then, Inertia requests the rooms.index route as a XHR request and before it hits your Controller, it passes through the HandleInertiaRequests middleware.

class HandleInertiaRequests extends Middleware
{
    public function share(Request $request)
    {
        return array_merge(parent::share($request), [
            'flash' => [
                'message' => fn () => $request->session()->get('message')
            ],
        ]);
    }
}

Now you can access it in your component via:

Options API

<template>
  <main>
    <header></header>
    <content>
      <div v-if="$page.props.flash.message" class="alert">
        {{ $page.props.flash.message }}
      </div>
      <slot />
    </content>
    <footer></footer>
  </main>
</template>

Composition API

<template>
  <main>
    <header></header>
    <content>
      <div v-if="message" class="alert">
        {{ message }}
      </div>
      <slot />
    </content>
    <footer></footer>
  </main>
</template>

<script>
import { computed } from 'vue'
import { usePage } from '@inertiajs/inertia-vue3'

export default {
  setup() {
    const message = computed(() => usePage().props.value.flash.message)
    return { message }
  },
}
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM