I
I
ideagood2021-08-22 17:16:41
Laravel
ideagood, 2021-08-22 17:16:41

How to get an authorized user?

I just started to learn api in laravel + vue bundle, and I can't figure out how to get an authorized user. I'm trying to do it like this:
Controller

public function login(Request $request)
    {
        $credentials = $request->only('email', 'password');
        if (Auth::attempt($credentials, true)) {
            return Auth::user();
        }
        throw ValidationException::withMessages([
            'errors' => ['Логин или пароль не совпадает']
        ]);
    }

api routes:
Route::middleware('auth:api')->get('/user', function (Request $request) {
    return $request->user();
});
Route::post('/login', [UserController::class, 'login']);

code in vue component
<template>
    <div class="container">
                <form @submit.prevent>
                    <div class="form-group mt-3">
                        <label class="text-white" for="email">Email</label>
                        <input v-model="form.email" type="text" name="email" class="form-control" id="email" aria-describedby="emailHelp" placeholder="email">
                    </div>
                    <div class="form-group mt-3">
                        <label class="text-white" for="password">Пароль</label>
                        <input v-model="form.password" type="password" name="password" class="form-control" id="password" placeholder="Пароль">
                    </div>
                    <button @click="loginUser" type="submit" class="btn my-btn-color mt-3">Войти</button>
                </form>
    </div>
</template>
<script>
export default {
    name: "LoginPage",
    data() {
        return {
            form: {
                email: '',
                password: '',
            },
        }
    },
    methods:{
        async loginUser(){
            try {
                await axios.post('api/login', this.form)
                const response = await axios.get('api/user')
                alert(response.data)
                await this.$router.push({name: 'home'})
            } catch (e) {
                console.log(e)
                this.errors.push(e.response.data.errors)
            }
        },
    }
}
</script>

401 error in logs
Error: Request failed with status code 401
What am I doing wrong?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question