I am calling a Laravel api endpoint http://localhost:8000/api/adduser
from a Vue Js component. The endpoint is suppose to set a value e.g a token to session, which I would fetch later. The endpoint is called successfully, however the session is not set. The code for my endpoint is
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Auth;
use App\User;
use Hash;
use Session;
class UserController extends Controller
{
public function adduser(Request $request) {
$user = User::where( 'sub', $request->sub )->first();
if(!$user) {
$user = new User();
$user->nickname = $request->nickname;
$user->name = $request->name;
$user->sub = $request->sub;
$user->api_token = $request->api_token;
$user->save();
}
$user->api_token = $request->api_token;
$user->save();
//setting session here
session(['info' => 'hello world']);
Session::save();
return response()
->json([
'done' => $user->api_token
]);
}
}
The Vue Js component which calls the endpoint is:
<template>
<div class="callback">Callback</div>
</template>
<script>
import axios from 'axios'
import Flash from '@/helpers/flash'
export default {
name: 'callback',
mounted() {
this.$auth.handleAuthentication().then((data) => {
//this.$router.push({ name: 'home' })
let form = {nickname: this.$auth.user.nickname,
name: this.$auth.user.name,
sub: this.$auth.user.sub,
api_token: this.$auth.api_token}
Flash.setSuccess('You have successfully signed in.')
axios({
method: 'post',
url: 'http://localhost:8000/api/adduser',
data: form
}).then((res) => {
if(res.data) {
window.location.href = "/";
}
})
.catch((err) => {
if(err.response.status === 422) {
this.error = err.response.data.errors
console.log(this.error)
}
});
})
}
}
</script>
To test if the session was set, I tried retrieving the session data from the welcome.blade.php
file, like so dd
but this returns null. What am I missing here?
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire