Search code examples
laravelvue.jsvuejs3laravel-9inertiajs

How to get redirected to a welcome page with a passed username prop using Inertia.js in Laravel 9?


I'm working on an Application with Laravel, vue.js (Inertia). There is a login page when the user enters the credentials, and if he is authenticated, he should be redirected to the "Welcome.vue," and I want to pass the username with it.

I have a login component that is accessible at "http://127.0.0.1:8000/Login" When the user fills out the form and hits the "login" now button following controller code is executed (which is working fine).

This is my controller code

public function login(Request $request)
{
    $credentials = $request->only('email', 'password');
    if (Auth::attempt($credentials)) {
        $username =Auth::user();
        return Inertia('Welcome', [
            'username' => $username
          ]);
    } else {
        return back()->with('message','Authenticaiton Failed');
    }
}

Now I can receive it as a propos. But the problem with this method is that the page URL remain the same which is "http://127.0.0.1:8000/Login"

I want to change it to "http://127.0.0.1:8000/Welcome".

I can use the return redirect('Welcome')->with('username',$username); but I can't receive it as a prop. I don't know what's the exact issue.

Following is the additional code that you might need:

Route Welcome

Route::get('/Welcome', function () {
    return inertia('Welcome');
    
})->name('Welcome')->middleware('auth', 'AuthenticateCustom');

Route Login

Route::get('/Login', function () {
    return inertia('Login');
})->name('Login');

Route::post('/Login', [UserController::class, 'login'])->name('login');

Any leads or suggestions would be highly appreciated.


Solution

  • There's no need for you to pass the username of the authenticated user and just redirect to the Welcome page. The HandleInertiaRequest middleware will handle that for you. If you want to access the authenticated user information you can just use the usePage()

    Inside <script setup> tag

    <script setup>
    import { computed } from 'vue'
    import { usePage } from '@inertiajs/vue3'
    
    const username = computed(() => {
        usePage().props.auth.user.username
    })
    </script>
    

    Inside the <template> tag

    <template>
        <span>{{ $page.props.auth.user.username }}</span>
    <template>