DEV Community

graigDev
graigDev

Posted on

How to use inertiaJs and Vue to retrieve data from a Laravel controller without redirection

Create a Controller which return a Validation exception

use Illuminate\Validation\ValidationException;

public function __invoke()
{
     $users = User::get();
     throw ValidationException::withMessages([
          'users' => $users,
      ]);
}
Enter fullscreen mode Exit fullscreen mode

In your vue component:

import { router } from '@inertiajs/vue3';

const users = ref([])

onMounted(() => {
   router.get('...your route path...', {}, {
      preserveState: true,
      preserveScroll: true,
      onError: (error) => {
         users.value = error.users
      }
   })
})
Enter fullscreen mode Exit fullscreen mode

Call your controller in web.php

Enjoy!

Top comments (0)