Laravel logout route in Vue component - laravel-5

In my Laravel 5.5 project I have a Vue component as a separate file with .vue extension.
In its template there is a vue-router link. Also, I need to place the standard Laravel logout link here.
<template>
<div>
<ul class="nav navbar-nav">
<li><router-link to="/">Home</router-link></li>
<!-- place where I want to add Laravel logout link -->
</ul>
</div>
</template>
I have tried to insert the Laravel logout link like this:
<template>
<div>
<ul class="nav navbar-nav">
<li><router-link to="/">Home</router-link></li>
<li>
<a href="{{ route('logout') }}" onclick="event.preventDefault();
document.getElementById('logout-form').submit();">
Logout
</a>
<form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;">
{{ csrf_field() }}
</form>
</li>
</ul>
</div>
</template>
But the code does not compile in this case. I see I can't use Laravel routes in Vue component. What can I do in this case?

You can define a method to call logout route
you can't use laravel blade syntax inside vue component
<template>
<div>
<ul class="nav navbar-nav">
<li><router-link to="/">Home</router-link></li>
<li>Logout</li>
</ul>
</div>
</template>
<script>
export default {
data: () => ({
csrf: document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
}),
methods:{
logout:function(){
axios.post('logout').then(response => {
if (response.status === 302 || 401) {
console.log('logout')
}
else {
// throw error and go to catch block
}
}).catch(error => {
});
},
},
}
</script>
note:
here i used axios for http requests, if you have no idea about that then you can also use normal ajax request
for csrf token you should include csrf data in your meta tag.

Well, Laravel adds csrf token automatically in axios request. So this code is working for me
<template>
<span>
Logout
</span>
</template>
<script>
export default {
name: "Logout",
methods: {
logout() {
axios.post('/logout')
.catch(error => {
window.location.href = '/login';
});
}
}
}
</script>

Related

No match found for location with path - Laravel 8 and Vue 3

Hi I have read that this question is already answered but that answer did not work to me.. I have my code like this:
/router/index.js
import { createRouter, createWebHistory } from 'vue-router'
const routes = [
{
path: '/login',
name: 'login',
component: () => import('../views/LoginView.vue')
}
]
const router = createRouter({
history: createWebHistory('/laravel-vue3/'),
routes
})
export default router
My app.js
import { createApp } from 'vue'
import App from './App.vue'
import router from './router/index.js'
createApp(App).use(router).mount('#app');
My .htaccess works without public in the path.
I am working in localhost so I go http://localhost/laravel-vue3 to go to the website
BUT it does not work.
I have my router view in App.vue like this:
<template>
<div>
<nav class="navbar navbar-expand-md navbar-light bg-white shadow-sm">
<div class="container">
<a class="navbar-brand" href="">
Portal Conecta Mayor
</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="{{ __('Toggle navigation') }}">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<!-- Left Side Of Navbar -->
<ul class="navbar-nav me-auto">
</ul>
<!-- Right Side Of Navbar -->
<ul class="navbar-nav ms-auto">
<!-- Authentication Links -->
<li class="nav-item">
<router-link class="nav-link" to="/login">Login</router-link>
</li>
<li class="nav-item">
<a class="nav-link" href="">Register</a>
</li>
</ul>
</div>
<router-view />
</div>
</nav>
</div>
</template>
<script>
export default {
}
</script>
When I go to http:localhost/larave-vue3 it opens my App.vue and it works BUT I receive this message:
[Vue Router warn]: No match found for location with path "/laravel-vue3/"
I added that to history: createWebHistory and it still does not work.
When I click login it displays this error:
Look the error
How can I fix the router problem in vue 3 with Laravel 8? Thanks

UserController not found

i have my blade file like this:
<div class="nav-item dropdown">
#if (Auth::check())
{{ Auth::user()->name }}
<div class="dropdown-menu">
Profile
My Order
<a href="#" class="dropdown-item" onclick="event.preventDefault(); document.getElementById('logout-form').submit();">
Logout </a>
<form id="logout-form" action="{{ route('logout') }}" method="POST" class="d-none">
#csrf
</form>
</div>
#else
<div class="nav-item dropdown">
Login
<div class="dropdown-menu">
Customer
Register
</div>
</div>
#endif
</div>
and my router like this:
/multi-auth router
Route::prefix('user') ->name ('user.') ->group (function(){
Route::middleware (['guest']) ->group (function(){
Route::view('/login', 'dashboard.user.login') ->name ('login');
Route::view('/register', 'dashboard.user.register') ->name ('register');
});
Route::middleware(['auth']) ->group(function(){
Route::view('/home', 'dashboard.user.home') ->name ('home');
});
});
i have already add use App\Http\Controllers\UserController; in the web.php but i still get that UserController cannot found. I really dont know where i am wrong. Is it perhaps i dont use Route::has (user.login)?
i am using laravel/ui but i have changed my blade to the one i wrote above
but you didnt mention the UserCotroller in your route? how do you expect ot to find it ? you are returning views through your route, you are not redirectting it to your controller
here is how you should declare it :
Route::get('/register', [UserController::class, 'create'])
->middleware('guest')
->name('register');
Route::post('/register', [UserController::class, 'store'])
->middleware('guest');
Route::get('/login', [UserController::class, 'create'])
->middleware('guest')
->name('login');
Route::post('/login', [UserController::class, 'store'])
->middleware('guest');
and in the create method you can write
return view(dashboard.user.login);

TypeError: this.axios is undefined

I'm having this error in browser console, no matter what I did.
First of all I'm new in VueJS. My site is fully functioning, it's build with Laravel. I am trying to convert the frontend to VueJS. I'm trying retrieve data from database and show them in front page using VueJS.
app.js
require('./bootstrap');
window.Vue = require('vue');
//Vue.component('example-component', require('./components/ExampleComponent.vue').default);
Vue.component('title-bar',require('./components/front/titleBar.vue').default);
Vue.component('info-bar',require('./components/front/infoBar.vue').default);
import axios from 'axios';
Vue.use(axios);
const app = new Vue({
el: '#app',
});
infoBar.js
<template>
<div class="container">
<div class="row align-items-center justify-content-between mx-0">
<ul class="list-inline d-none d-lg-block mb-0">
<li class="list-inline-item mr-3">
<div class="d-flex align-items-center">
<i class="ti-email mr-2"></i>
{{ info.email }}
</div>
</li>
<li class="list-inline-item mr-3">
<div class="d-flex align-items-center">
<i class="ti-headphone mr-2"></i>
{{ info.phone }}
</div>
</li>
</ul>
<ul class="list-inline mb-0">
<li class="list-inline-item mr-0 p-3 border-right border-left border-white-0_1">
<span>EIIN: {{ info.eiin }}</span>
</li>
<li class="list-inline-item mr-0 p-3 border-right border-white-0_1">
<span>Institute Code: {{ info.code }}</span>
</li>
</ul>
<ul class="list-inline mb-0">
<li class="list-inline-item mr-0 p-md-3 p-2 border-right border-left border-white-0_1">
Login
</li>
</ul>
</div> <!-- END END row-->
</div> <!-- END container-->
</template>
<script>
export default {
data() {
return {
info: {}
}
},
created() {
this.axios
.get('http://localhost/wpschool/public/api/info-bar')
.then(response => {
this.info = response.data;
console.log(response.data)
});
}
}
</script>
api.php
<?php
use Illuminate\Http\Request;
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
Route::get('info-bar','FrontController#infoBar');
Route::get('title-bar','FrontController#titleBar');
controller
public function infoBar()
{
$info = [
'email' => siteConfig('email'),
'phone' => siteConfig('phone'),
'eiin' => siteConfig('eiin'),
'code' => siteConfig('institute_code')
];
return response($info);
}
In Vue console the <info-bar> component is returning with empty object. The console is returning with two errors about axios
[Vue warn]: Error in created hook: "TypeError: this.axios is undefined"
found in
---> at resources/js/components/front/infoBar.vue
and
TypeError: this.axios is undefined
Choo 29
I tried reinstalling axios but same result.
Inside app.js add this line of code:
Vue.prototype.axios = axios;
After this statement, you can use this.axios inside every Vue component
On app.js, use
window.axios = require("axios");
// instead of
import axios from 'axios';
Vue.use(axios);
on Vue files, use like this:
axios.get(...)

how i can use vuejs component in laravel blade?

the idea is to use vue component inside file blade but i got this error
Failed to mount component: template or render function not defined.
this my importation in app.js
Vue.component('Notification' ,require('./components/Notification.vue'));
this my component code
<template>
<li class="nav-item dropdown">
<a class="nav-link" data-toggle="dropdown" href="#">
<i class="fas fa-bell"></i> <span class="badge badge-light">{{unreads.length}}</span>
<span class="badge badge-warning navbar-badge"></span>
</a>
<div class="dropdown-menu dropdown-menu-lg dropdown-menu-right">
<notification-item> </notification-item>
</div>
</li>
</template>
<script>
export default {
props :['unreads','userid'],
mounted() {
Echo.private('App.User.'+ this.userid)
.notification((notification) => {
console.log(notification);
});
}
}
</script>
and finally this my code in home.blade.php
<Notification :userid="{{auth()->id()}}" :unreads="{{auth()->user()->unreadNotifications}}"> </Notification>
someone help me please
Compile vuejs files via npm run dev and make sure that you use the correct binding for userid and include app.js into scripts.

VueJs With Laravel

I am learning Vuejs. I am making a system where users can set a message as favourite.
But i am getting the below error. Any help to resolve would be appreciated.
[Vue warn]: Failed to mount component: template or render function not
defined. found in
---> Favorite Root
Below is my code =>
Favorite.vue
<template>
<span>
<a href="#" v-if="isFavorited" #click.prevent="unFavorite(post)">
<i class="fa fa-heart"></i>
</a>
<a href="#" v-else #click.prevent="favorite(post)">
<i class="fa fa-heart-o"></i>
</a>
</span>
</template>
<script>
export default {
name: 'favorite',
props: ['post', 'favorited'],
data: function() {
return {
isFavorited: '',
}
},
mounted() {
this.isFavorited = this.isFavorite ? true : false;
},
computed: {
isFavorite() {
return this.favorited;
},
},
methods: {
favorite(post) {
axios.post('/favorite/'+post)
.then(response => this.isFavorited = true)
.catch(response => console.log(response.data));
},
unFavorite(post) {
axios.post('/unfavorite/'+post)
.then(response => this.isFavorited = false)
.catch(response => console.log(response.data));
}
}
};
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
app.js
require('./bootstrap');
window.Vue = require('vue');
/**
* Next, we will create a fresh Vue application instance and attach it to
* the page. Then, you may begin adding components to this application
* or customize the JavaScript scaffolding to fit your unique needs.
*/
Vue.component('Favorite', require('./components/Favorite.vue'));
const app = new Vue({
el: '#app'
});
index.blade.php
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel">
<h3>All Posts</h3>
<hr>
</div>
#forelse ($posts as $post)
<div class="card">
<div class="card-header">
{{ $post->title }}
</div>
<div class="card-body mb-2">
{{ $post->body }}
</div>
#if (Auth::check())
<div class="card-footer mb-2">
<favorite
:post={{ $post->id }}
:favorited={{ $post->favorited() ? 'true' : 'false' }}
></favorite>
</div>
#endif
</div>
#empty
<p>No post created.</p>
#endforelse
{{ $posts->links() }}
</div>
</div>
</div>
#endsection
Try Vue.component('Favorite', require('./components/Favorite.vue').default); with .default at the end.

Resources