How to return using a link from a Vue component to Laravel Web Route? - laravel

My component where I want to route to Laravel Notice the question in the href in the script: The idea is actually to return me from the Vue component to a Laravel view. I have realized that vue router allows me to go perfectly from one vue component to another vue component and what I need is to go from a link in a vue component to a laravel view that belongs to a web route
<template>
<div>
<v-breadcrumbs
:items="items"
divider="."
></v-breadcrumbs>
</div>
</template>
<script>
export default {
data: () => ({
items: [
{
text: 'Dashboard',
disabled: false,
href: 'how do i add a laravel web route here?',
},
{
text: 'Link 1',
disabled: false,
href: 'breadcrumbs_link_1',
},
{
text: 'Link 2',
disabled: true,
href: 'breadcrumbs_link_2',
},
],
}),
}
</script>

Related

vue3 i18n, how to combine Vue Router + i18n?

I would like to combine i18n with the Vue Router (vue3). I can setup the i18n module successfully but the integration into the routing system always fails.
The router-view is located in App.vue:
<template>
<div class="container">
<!-- Content here -->
<the-header></the-header>
<router-view></router-view>
</div>
</template>
<script>
import TheHeader from './components/TheHeader.vue'
export default {
name: 'App',
components: {
TheHeader
}
}
</script>
I access the language routes via a global object $t. The languager switcher works. So the following router-links in the TheHeader component contain the right paths to the language specific components (this.$i18n.locale always returns the right path-fragment: eg: 'en','de' etc.., this works!!):
<ul class="navbar-nav">
<li class="nav-item">
<router-link class="nav-link active" aria-current="page"
:to="`/${this.$i18n.locale}/home`">{{ $t('nav.home') }}</router-link>
</li>
<li class="nav-item">
<router-link class="nav-link" :to="`/${this.$i18n.locale}/about`">{{ $t(`nav.about`) }}
</router-link>
</li>
Now I stuck with the router. I found the following example here, but it does not work:
const router = createRouter({
history: createWebHistory(),
routes: [
{
path: "/:lang",
component: {
render: (h) => h("router-view"),
},
children: [
{
path: "home",
name: "home",
component: Home,
},
{
path: "design",
name: "design",
component: Design,
},
{
path: "about",
name: "about",
component: About,
},
{
path: "contact",
name: "contact",
component: Contact,
},
],
},
],
});
stack trace:
Uncaught (in promise) TypeError: h is not a function
at Proxy.render (router.js?41cb:15)
at renderComponentRoot (runtime-core.esm-bundler.js?5c40:464)
at ReactiveEffect.componentUpdateFn [as fn] (runtime-core.esm-bundler.js?5c40:4332)
at ReactiveEffect.run (reactivity.esm-bundler.js?a1e9:160)
at setupRenderEffect (runtime-core.esm-bundler.js?5c40:4458)
at mountComponent (runtime-core.esm-bundler.js?5c40:4241)
at processComponent (runtime-core.esm-bundler.js?5c40:4199)
at patch (runtime-core.esm-bundler.js?5c40:3791)
at ReactiveEffect.componentUpdateFn [as fn] (runtime-core.esm-bundler.js?5c40:4409)
at ReactiveEffect.run (reactivity.esm-bundler.js?a1e9:160)
Principally, the language switcher should work independently from the router, with the independent global variable $t. However, I need the complete path in the URL, I need an integration of i18n into the router! How can I configure the Vue Router correctly?
import { h, resolveComponent } from "vue";
path: "/:lang",
component: {
render() {
return h(resolveComponent("router-view"));
},
},

How to pass a value from Laravel blade to a vue component?

I am working on laravel / vue project and i want to pass a value from laravel blade to the vue component but i get this error :
Missing required prop: "id" at
The vue component:
export default {
props:{
id:{
required : true
}
},
mounted() {
console.log(this.id)
},
}
The Laravel blade:
<div id="add_product">
<add-product :id="{{$product_id}}"></add-product>
</div>
https://router.vuejs.org/guide/essentials/passing-props.html
you should add props true to router
{ path: '/user/:id', component: User, props: true },
Edit :
Just remove : from :id
<add-product id="{{$product_id}}"></add-product>

How to display records from Laravel via Vuetify v-data-table component

I have a project build in Laravel with Vue.js which work perfect statically, but I need convert it into dynamically to pull records from database table to v-data-table component.
I know Laravel and I know How these things works via Ajax/jQuery but I'm pretty new in Vue.js
Can someone explain to me how to display the results from the database in the v-data-table component.
Thanks.
Here is the Vue.js file:
<template>
<v-app>
<v-main>
<div>
<v-tab-item>
<v-card flat>
<v-card-text>
<v-card-title>
<v-spacer></v-spacer>
<v-text-field
v-model="search"
append-icon="mdi-magnify"
label="Search"
single-line
hide-details
></v-text-field>
</v-card-title>
<v-data-table
:headers="headers"
:items="items"
:items-per-page="5"
class=""
:search="search">
</v-data-table>
</v-card-text>
</v-card>
</v-tab-item>
</div>
</v-main>
</v-app>
</template>
<script>
export default {
data: () => ({
search: '',
items: [],
headers: [
{
text: '#',
align: 'start',
sortable: false,
value: 'id',
},
{ text: 'Name', value: 'name' },
{ text: 'Slug', value: 'slug' },
],
/*THIS IS A STATIC DATA*/
// items: [
// {
// id: 1,
// name: 'Test Name 1',
// slug: 'test-name-1',
// },
// {
// id: 2,
// name: 'Test Name 2',
// slug: 'test-name-2',
// },
// ],
/*THIS IS A STATIC DATA*/
}),
created () {
this.getItems();
},
methods: {
getItems() {
axios
.get('/test/vue')
.then((response) => {
this.items = response.data,
console.log(response.data)
})
.catch(error => console.log(error))
},
}
}
</script>
And Here is Blade file:
#extends('it-pages.layout.vuetify')
#section('content')
<div id="appContainer">
<software-template></software-template>
</div>
Output in the console is :
console.log
Response from axios is also Ok
response
My Controller :
public function showData()
{
$items = Category::select('id', 'name', 'slug')->where('order', 1)->get();
// dd($items);
return response()->json(['items' => $items]);
}
My route:
Route::get('test/vue', 'PagesController#showData');
console.log after changes axios lines
console-log
So there were multiple issues here:
The backend did you return a correct array
The frontend performed a post request instead of a get
The this context is not correct since you are using a function instead of arrow syntax
Make sure to look at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions and read about how this changes how this is elevated.
In your case, you need to change the code on the then part of your axios call:
.then((response) => {
this.items = response.data
})
I must to say that I solve the problem.
Problem was been in axios response.
Instead this.items = response.data I change to this.items = response.data.items and it work perfectly.
methods: {
getItems() {
axios
.get('/test/vue')
.then((response) => {
this.items = response.data.items
console.log(response.data.items)
})
.catch(error => console.log(error))
},
}

Vue - Vue routes doesn´t exist

I have a project in Laravel + Vue. In Laravel i have some routes for create endpoints and start page.
Laravel Routes
Route::get('/', 'Auth\LoginController#showLoginForm');
Route::post('/login', 'Auth\LoginController#login');
Auth::routes();
Route::resource('gateways', 'GatewayController');
Route::resource('contadores', 'ContadorController');
'/' route go to Blade file with Login Component.
Login Component has this code.
<template>
<v-content slot="content">
<v-container class="fill-height" fluid>
<v-row align="center" justify="center">
<v-col cols="12" md="8">
<v-card class="elevation-12">
<v-toolbar dark flat>
<v-toolbar-title>LoRaWAN</v-toolbar-title>
</v-toolbar>
<v-card-text>
<v-form>
<v-text-field
label="Usuario"
name="username"
prepend-icon="mdi-account"
type="text"
v-model="username"
/>
<v-text-field
label="Contraseña"
name="password"
prepend-icon="mdi-key"
:append-icon="value ? 'mdi-eye' : 'mdi-eye-off'"
#click:append="() => (value = !value)"
:type="value ? 'password' : 'text'"
v-model="password"
/>
</v-form>
</v-card-text>
<v-card-actions>
<v-btn block dark #click="submit()">Entrar</v-btn>
</v-card-actions>
</v-card>
</v-col>
</v-row>
</v-container>
</v-content>
</template>
<script>
export default {
data() {
return {
value: String,
username: "",
password: ""
};
},
methods: {
submit() {
axios
.post("http://127.0.0.1:8000/login", {
username: this.username,
password: this.password
})
.then(response => {
if (response.data.token != null) {
localStorage.setItem("token", response.data.token);
console.log("ok");
this.$router.push({
name: "lora",
params: { user: this.username }
});
}
})
.catch(function(errors) {
let error = errors.response.data.errors;
let mensaje = "Error no identificado";
if (error.hasOwnProperty("username")) {
mensaje = error.username[0];
} else {
mensaje = error.password[0];
}
Swal.fire({
title: "Error",
text: mensaje,
icon: "error",
confirmButtonText: "Ok"
});
});
}
}
};
</script>
As we can see when login endpoint return token we want to push to other 'lora' route.
Vue routes file
import ContadorComponent from "./components/contador/ContadorComponent.vue";
import GatewayComponent from "./components/gateway/GatewayComponent.vue";
import HomeComponent from "./components/home/HomeComponent.vue";
import MainComponent from "./components/main/MainComponent.vue";
const routes = [{
path: "/lora",
name: "lora",
component: MainComponent,
props: true,
children: [{
path: "",
name: "home",
component: HomeComponent
},
{
path: "contadores",
name: "contadores",
component: ContadorComponent
},
{
path: "gateways",
name: "gateways",
component: GatewayComponent
}
]
}];
const router = new VueRouter({
mode: 'history',
routes: routes
});
new Vue({
vuetify: new Vuetify(),
router
}).$mount("#app");
And lora route (Main Component)
<template>
<v-app id="app">
<layoutDrawer></layoutDrawer>
<layoutHeader></layoutHeader>
<v-content>
<router-view></router-view>
</v-content>
<layoutFooter></layoutFooter>
</v-app>
</template>
<script>
import layoutHeader from "./partials/HeaderComponent.vue";
import layoutFooter from "./partials/FooterComponent.vue";
import layoutDrawer from "./partials/SidebarComponent.vue";
export default {
props: {
username: { type: String, default: "Invitado" }
},
components: {
layoutHeader,
layoutDrawer,
layoutFooter
}
};
</script>
The problem: If i go to http://127.0.0.1:8000/lora returns that this route doesn´t exist. In the vue routes file i declare it, so i don´t know why returns this. Maybe Laravel generate a conflict or something with routes. In laravel routes file i test this code and works
Route::get('/test', function () {
return view('home');
})->name('home');
The view home is blade file with Main Component. Maybe something happens with the vue routes that project doesn't recognize and only works Laravel routes..
The question: Are the vue routes properly declares? Anybody see some error?
Your client and server are running on the same port: http://127.0.0.1:8000.
The url for your lora route should be something like http://127.0.0.1:8001/lora
I found a partially solution. In Laravel routes i need to put this
Route::get('{any?}', function () {
return view('layout');
})->where('any', '.*');
Every time the user push to another page load Layout blade.
#extends('layouts.app')
#section('content')
<layout-component></layout-component>
#endsection
Layout Component
<template>
<v-app id="app">
<router-view></router-view>
</v-app>
</template>

How to Authenticate User using Laravel Api routes and Vue 2 Js and Vue Router

My goal is that laravel has an implemented Authorization Provider for us
https://laravel.com/docs/5.3/authentication
so I want to authenticate my users by using that by an API and set it back to my Vue Router
and authorize the users
How can i implement it?
Im always getting an error on authentication
im using axios as my HTTP provider
Here is the app.js
require('./bootstrap');
import VueRouter from 'vue-router';
import Vue from 'vue'
import axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(VueAxios, axios)
Vue.use(VueRouter);
axios.defaults.baseURL = '/api';
axios.defaults.headers.common['X-CSRF-TOKEN'] = window.Laravel.csrfToken;
import LoginForm from './components/LoginForm.vue';
import RegisterForm from './components/RegisterForm.vue';
Vue.component('login-form',LoginForm)
Vue.component('register-form',RegisterForm)
// Directives
const routes = [
{ path: '/', component: require('./pages/Index.vue') },
{ path: '/admin/users', component: require('./pages/admin/Users.vue') },
{ path: '/user/:id', component: require('./pages/user/Dashboard.vue'),
children: [
// UserHome will be rendered inside User's <router-view>
// when /user/:id is matched
{ path: '', component: require('./pages/user/Index.vue')},
// UserPosts will be rendered inside User's <router-view>
// when /user/:id/posts is matched
{ path: 'settings', component: { template: '<div>Settings</div>' } },
]
},
{ path: '/manager/:id', component: require('./pages/user/Dashboard.vue'),
children: [
// UserHome will be rendered inside User's <router-view>
// when /user/:id is matched
{ path: '', component: require('./pages/user/Index.vue')},
// UserPosts will be rendered inside User's <router-view>
// when /user/:id/posts is matched
{ path: 'settings', component: require('./pages/user/Settings.vue') },
]
},
{ path: '/store/:id', component: require('./pages/user/Dashboard.vue'),
children: [
// UserHome will be rendered inside User's <router-view>
// when /user/:id is matched
{ path: '', component: require('./pages/user/Index.vue')},
// UserPosts will be rendered inside User's <router-view>
// when /user/:id/posts is matched
{ path: 'settings', component: { template: '<div>Settings</div>' } },
]
},
{ path: '/*', component: require('./pages/404.vue') },
];
const router = new VueRouter({
routes,
});
const app = new Vue({
el: '#app',
router,
template: `<div id="#app">
<router-view></router-view>
</div>`,
})
Here is the a Login form component
<template>
<form class="form" #submit.prevent='submitForm'>
<div class="form-group">
<input type="email" class="form-control" name="email" v-model="login.email" placeholder="Email">
</div>
<div class="form-group">
<input type="password" class="form-control" name="password" v-model="login.password" placeholder="Password">
</div>
<div class="form-group">
<button type="submit" class="btn btn-info btn-block"> Login </button>
</div>
</form>
</template>
<script>
export default {
data() {
return {
errors: [],
login: {
email: '',
password: '',
_token: window.Laravel.csrfToken
}
}
},
methods: {
submitForm() {
this.axios.post('/login',this.login)
.then(response => {
})
.catch(response => {
})
}
}
}
</script>
this is my Laravel API
in api.php
<?php
use Illuminate\Http\Request;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::group(['middleware' => 'auth'], function () {
Route::get('/auth',function() {
return Auth::user();
});
Route::resource('/users','UserController');
Route::resource('/stores','StoreController');
Route::resource('/items','ItemController');
Route::resource('/transactions','StoreController');
Route::resource('/managers','ManagerController');
Route::resource('/employees','EmployeeController');
Route::resource('/customers','CustomerController');
Route::resource('/tags','TagController');
});
Route::group(['middleware' => 'web'], function() {
Auth::routes();
});
So my BIG PROBLEM here is the authentication using vue i'm used to authentication in blade templates and laravel routes but not on vue

Resources