pass parameter in URL using vuejs and laravel - laravel

I wanna display data with specefic ID in laravel using vuejs.
I get the ID from the link but it seems that there is no request sent to the controller.
api.php :
<?php
use Illuminate\Http\Request;
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
Route::resource('user','API\UserController');
Route::resource('departement','API\DepartementController');
Route::resource('specialite','API\SpecialiteController')->parameters(['specialite'=>'id']);
my controller :
public function show($id)
{
$specialite=Specialite::with('dep')->findOrFail($id);
$spec = Specialite::with('dep')->where('id',$specialite)->get();
return $spec;
}
my view :
<script>
export default {
data(){
return{
specialites:{},
form: new Form({
id:'',
name:'',
user_id:'',
bio:''
}),
id:0,
}
},
methods: {
loadspecialite(){
//axios.get('api/user').then(({data})=>(this.enseignants=data.data));
axios.get('api/specialite/'+this.id).then(response=>{this.specialites=response.data;});
},
created() {
this.id=this.$route.params.id;
this.loadspecialite();
Fire.$on('AfterCreate',()=>{
this.loadspecialite();
})
}
}
</script>
Vue-router:
let routes = [
{ path: '/Profile/:id', component: require('./components/a.vue').default },
]
thank you.
hope tou will help me.

Firstly, I don't see how this.id would carry the id from the router as created is not guaranteed to have been fired AFTER the router has routed.
Your loadspecialite should get the value from the currentRoute when called and i think the var is slightly wrong:
let id = this.$router.currentRoute.params.id;
Your route resource should be:
Route::resource('specialite','API\SpecialiteController');
The request uri would be:
axios.get(`/api/specialite/${id}`).then(...)
You can find out the exact uri path for all registered routes in Laravel by using an SSH terminal to run console command: php artisan route:list
This should produce the following:
+--------+-----------+----------------------------------+------------------------+------------------------------------------------------------------------+--------------+
| Domain | Method | URI | Name | Action | Middleware |
+--------+-----------+----------------------------------+------------------------+------------------------------------------------------------------------+--------------+
| | GET|HEAD | api/specialite | api.specialite.index | App\Http\Controllers\API\ApplicationController#index | api,auth:api |
| | POST | api/specialite | api.specialite.store | App\Http\Controllers\API\ApplicationController#store | api,auth:api |
| | GET|HEAD | api/specialite/create | api.specialite.create | App\Http\Controllers\API\ApplicationController#create | api,auth:api |
| | GET|HEAD | api/specialite/{specialite} | api.specialite.show | App\Http\Controllers\API\ApplicationController#show | api,auth:api |
| | PUT|PATCH | api/specialite/{specialite} | api.specialite.update | App\Http\Controllers\API\ApplicationController#update | api,auth:api |
| | DELETE | api/specialite/{specialite} | api.specialite.destroy | App\Http\Controllers\API\ApplicationController#destroy | api,auth:api |
| | GET|HEAD | api/specialite/{specialite}/edit | api.specialite.edit | App\Http\Controllers\API\ApplicationController#edit | api,auth:api |
P.S. there is no need to create a form object if you are not sending any attached files, Laravel and axios will revert to use JSON by default with ajax requests.
Laravel will return JSON object by default in response to a JSON ajax call direct from a resource on your controller:
function show($id) {
return Specialite::findOrFail($id);
}
Fail will return a 400+ header that in turn can be handled by axsios .catch
.catch( error => { console.log(error.response.message) } )
Laravel from validation messages would be accessible via:
.catch( error => { console.log(error.response.data.errors) } )
Axios will post an object/array as a JSON request:
data() {
return {
form: {
id:'',
name:'',
user_id:'',
bio:''
},
}
}
...
axios.post('/api/specialite',this.form).then(...);

I do believe that the code is functioning fine. It is a formatting error in the vue component object. Basically your created() handler is in the due methods, thus it won't be handled when the created event is done.
// your code snippet where there is an issue
methods: {
loadspecialite(){
//axios.get('api/user').then(({data})=>(this.enseignants=data.data));
axios.get('api/specialite/'+this.id).then(response=>{this.specialites=response.data;});
}, // end of loadspecialite
created() {
this.id=this.$route.params.id;
this.loadspecialite();
Fire.$on('AfterCreate',()=>{
this.loadspecialite();
})
} // end of created
} //end of methods
What you should do is just remove the created() out of methods and also check the syntax of the function again.
const Foo = {
template: '<div>foo</div>'
}
const Bar = {
template: '<div><span> got {{form}}</span></div>',
data() {
return {
specialites: {},
form: 'fetching...',
id: 0,
}
},
methods: {
loadspecialite() {
// test method for getting some data
axios.get('https://httpbin.org/anything/' + this.id)
.then(response => {
this.form = response.data.url;
}).catch(error => {
console.error(error)
})
},
}, // <- this is the end of methods {}
/**
* Created method outside of methods scope
*/
created() {
this.id = this.$route.params.id;
this.loadspecialite();
}
}
// rest is vues demo router stuff
const routes = [{
path: '/foo',
component: Foo
},
{
path: '/bar/:id',
component: Bar
}
]
const router = new VueRouter({
routes // short for `routes: routes`
})
const app = new Vue({
router
}).$mount('#app')
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Vue Routed</title>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.min.js"></script>
<style>
button {
padding: 0.75rem;
background: #eee;
border: 1px solid #eaeaea;
cursor: pointer;
color: #000
}
button:active {
color: #000;
box-shadow: 0px 2px 6px rgba(0,0,0,0.1);
}
</style>
</head>
<body>
<div id="app">
<h1>Hello App!</h1>
<p>
<span> Click a button </span>
<router-link to="/foo"><button>Go to Foo</button></router-link>
<router-link to="/bar/3"><button>Go to Where it will get the data</button></router-link>
</p>
<!-- route outlet -->
<!-- component matched by the route will render here -->
<router-view></router-view>
</div>
</body>
</html>

All thing has set well, just your show method should respond in JSON:
use Illuminate\Http\Response;
function show($id) {
result = Specialite::findOrFail($id);
return response()->json($result,Response::HTTP_OK);
}

Related

nuxtjs + vue-native-websocket how to use?

I have component page. I need connect websocket after page ready;
<script lang="ts">
import Vue from 'vue'
import VueNativeSock from 'vue-native-websocket'
export default Vue.extend({
data() {
return {}
},
methods : {
senddata() {
this.$socket.sendObj({awesome: 'data'})
},
},
mounted(){
Vue.use(VueNativeSock, 'ws://cm2:3000', {
reconnection: true, // (Boolean) whether to reconnect automatically (false)
reconnectionAttempts: 5, // (Number) number of reconnection attempts before giving up (Infinity),
reconnectionDelay: 2000, // (Number) how long to initially wait before attempting a new (1000)
})
}
})
</script>
Everything connects fine, but if I try use $socket in method, I get error while building :
ERROR ERROR in pages/index.vue:20:9 15:42:05
TS2339: Property '$socket' does not exist on type 'CombinedVueInstance<Vue, {}, { senddata(): void; }, unknown, Readonly<Record<never, any>>>'.
18 | senddata() {
19 |
> 20 | this.$socket.sendObj({awesome: 'data'})
| ^^^^^^^
21 |
22 | },
23 |
What do I wrong ? The same if I put wss connection in plugin
The problem solved when I back to commonJS.

Trying to follow a tutorial to build a spring boot vuejs project but get some errors

I'm trying to follow this tutorial https://github.com/jonashackt/spring-boot-vuejs to build a spring boot with vuejs project, I have created the empty vue project using vue create frontend --no-git and then till this step: "Calling a REST service with Axios is simple. Go into the script area of your component, e.g. Hello.vue and add:"
import axios from 'axios'
data ();{
return {
response: [],
errors: []
}
},
callRestService ();{
axios.get(`api/hello`)
.then(response => {
// JSON responses are automatically parsed.
this.response = response.data
})
.catch(e => {
this.errors.push(e)
})
}
}
I don't know where exactly this should be added. I created my Hello.vue file under frontend\src\views folder like this and I added it in the src\router\index.js
<template>
<div class="hello">
<button class=”Search__button” #click="callRestService()">CALL Spring Boot REST backend service</button>
<h3>{{ response }}</h3>
</div>
</template>
<script>
import axios from 'axios'
data ();{
return {
response: [],
errors: []
}
},
callRestService ();{
axios.get(`api/hello`)
.then(response => {
// JSON responses are automatically parsed.
this.response = response.data
})
.catch(e => {
this.errors.push(e)
})
}
}
</script>
But the npm run build gives me this error:
C:\gitercn1\spring-boot-vuejs-copy\frontend\src\views\Hello.vue: 'return' outside of function (13:4)
11 |
12 | data ();{
> 13 | return {
| ^
14 | response: [],
15 | errors: []
16 | }
First, you must add callRestService() in methods or handler (as you are calling the method on button click).
Second, you should remove the unnecessary ; after data() and callRestService().
Third, you should export and name your component if you're going to reuse it somewhere.
Inside your Home.vue component, it could look like so:
<template>
<div class="hello">
<button class=”Search__button” #click="callRestService()">CALL Spring Boot REST backend service</button>
<h3>{{ response }}</h3>
</div>
</template>
<script>
import axios from 'axios'
export default {
name: "HelloComponent",
data() {
return {
response: [],
errors: []
}
},
methods: {
callRestService() {
axios.get(`api/hello`)
.then(response => {
// JSON responses are automatically parsed.
this.response = response.data
})
.catch(e => {
this.errors.push(e)
})
}
}
}
</script>

The show method in laravel return the index method instead

I have an issue trying to use the show method in a resource controller in laravel 5.7. I'm working with VueJS and axios to http requests. The index method is called instead show method. I'm pass do the call with get method and the ID param.
Routes:
POST | products | products.store | App\Http\Controllers\ProductoController#store | web |
| | GET|HEAD | products/create | products.create | App\Http\Controllers\ProductoController#create | web |
| | DELETE | products/{product} | products.destroy | App\Http\Controllers\ProductoController#destroy | web |
| | PUT|PATCH | products/{product} | products.update | App\Http\Controllers\ProductoController#update | web |
| | GET|HEAD | products/{product} | products.show | App\Http\Controllers\ProductoController#show | web |
| | GET|HEAD | products/{product}/edit | products.edit | App\Http\Controllers\ProductoController#edit | web |
web.php:
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
//Productos
Route::resource('products', 'ProductoController');
Route::get('duplicar/{param?}', 'ProductoExtController#duplicar');
Route::post('mostrarProductos', 'ProductoExtController#mostrarProductos');
Route::post('guardarValoresEditados', 'ProductoExtController#guardarValoresEditados');
Route::get('imprimirListadoPrecios', 'ProductoExtController#imprimirListadoPrecios');
Route::post('mostrarProductosStickers', 'ProductoExtController#mostrarProductosStickers');
Route::post('imprimirStickers','ProductoExtController#imprimirStickers');
//Colecciones
Route::resource('colecciones', 'ColeccionController');
//Categorias
Route::resource('categorias', 'CategoriaController');
//Crostas
Route::resource('crostas', 'CrostaController');
Route::get('crostasaut/{param?}', 'CrostaExtController#autocomplete');
//Folias
Route::resource('folias', 'FoliaController');
Route::get('foliasaut/{param?}', 'FoliaExtController#autocomplete');
Route::get('{path}', 'HomeController#index')->where('path','([A-z\d-\/_.]+)?');
And this is my http-request with axios:
editarProducto(pDatosFila){
axios.get('products', {
params: {
id: pDatosFila.f014_id
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
.then(function () {
// always executed
});
}
And to end this is the response:
current_page: 1
data: [{f014_id: 25, f014_id_old: null, f014_nombre: "carlos ruales", f014_deleted: null,…},…]
first_page_url: "http://localhost:8000/products?page=1"
from: 1
last_page: 1
last_page_url: "http://localhost:8000/products?page=1"
next_page_url: null
path: "http://localhost:8000/products"
per_page: 10
prev_page_url: null
to: 7
total: 7
What you are currently doing is :
axios.get('products', {
params: {
id: pDatosFila.f014_id
}
})
is equivalent to : axios.get('/products?id=id') (NOT THE RIGHT FORMAT)
What you need to do is :
axios.get('/products/product_id')
So, you can do something like :
axios.get('products/'+ pDatosFila.f014_id)
and this will work. :)
PS : always check the network tab in developer tools in browser.
Reference : axios

How to refetch a query when a new subscription arrives in react-apollo

I was wondering if there's an elegant way to trigger the refetch of a query in react-apollo when a subscription receives new data (The data is not important here and will be the same as previous one). I just use subscription here as a notification trigger that tells Query to refetch.
I tried both using Subscription component and subscribeToMore to call "refetch" method in Query's child component but both methods cause infinite re-fetches.
NOTE: I'm using react-apollo v2.1.3 and apollo-client v2.3.5
here's the simplified version of code
<Query
query={GET_QUERY}
variables={{ blah: 'test' }}
>
{({ data, refetch }) => (
<CustomComponent data={data} />
//put subscription here? It'll cause infinite re-rendering/refetch loop
)}
<Query>
Finally I figured it out myself with the inspiration from Pedro's answer.
Thoughts: the problem I'm facing is that I want to call Query's refetch method in Subscription, however, both Query and Subscription components can only be accessed in render method. That is the root cause of infinite refetch/re-rendering. To solve the problem, we need to move the subscription logic out of render method and put it somewhere in a lifecycle method (i.e. componentDidMount) where it won't be called again after a refetch is triggered. Then I decided to use graphql hoc instead of Query component so that I can inject props like refetch, subscribeToMore at the top level of my component, which makes them accessible from any life cycle methods.
Code sample (simplified version):
class CustomComponent extends React.Component {
componentDidMount() {
const { data: { refetch, subscribeToMore }} = this.props;
this.unsubscribe = subscribeToMore({
document: <SUBSCRIBE_GRAPHQL>,
variables: { test: 'blah' },
updateQuery: (prev) => {
refetch();
return prev;
},
});
}
componentWillUnmount() {
this.unsubscribe();
}
render() {
const { data: queryResults, loading, error } } = this.props;
if (loading || error) return null;
return <WhatEverYouWant with={queryResults} />
}
}
export default graphql(GET_QUERY)(CustomComponent);
It's possible if you use componentDidMount and componentDidUpdate in the component rendered by the Subscription render props function.
The example uses recompose higher order components to avoid too much boilerplating. Would look something like:
/*
* Component rendered when there's data from subscription
*/
export const SubscriptionHandler = compose(
// This would be the query you want to refetch
graphql(QUERY_GQL, {
name: 'queryName'
}),
lifecycle({
refetchQuery() {
// condition to refetch based on subscription data received
if (this.props.data) {
this.props.queryName.refetch()
}
},
componentDidMount() {
this.refetchQuery();
},
componentDidUpdate() {
this.refetchQuery();
}
})
)(UIComponent);
/*
* Component that creates the subscription operation
*/
const Subscriber = ({ username }) => {
return (
<Subscription
subscription={SUBSCRIPTION_GQL}
variables={{ ...variables }}
>
{({ data, loading, error }) => {
if (loading || error) {
return null;
}
return <SubscriptionHandler data={data} />;
}}
</Subscription>
);
});
Another way of accomplishing this while totally separating Query and Subscription components, avoiding loops on re-rendering is using Apollo Automatic Cache updates:
+------------------------------------------+
| |
+----------->| Apollo Store |
| | |
| +------------------------------+-----------+
+ |
client.query |
^ +-----------------+ +---------v-----------+
| | | | |
| | Subscription | | Query |
| | | | |
| | | | +-----------------+ |
| | renderNothing | | | | |
+------------+ | | | Component | |
| | | | | |
| | | +-----------------+ |
| | | |
+-----------------+ +---------------------+
const Component =() => (
<div>
<Subscriber />
<QueryComponent />
</div>
)
/*
* Component that only renders Query data
* updated automatically on query cache updates thanks to
* apollo automatic cache updates
*/
const QueryComponent = graphql(QUERY_GQL, {
name: 'queryName'
})(() => {
return (
<JSX />
);
});
/*
* Component that creates the subscription operation
*/
const Subscriber = ({ username }) => {
return (
<Subscription
subscription={SUBSCRIPTION_GQL}
variables={{ ...variables }}
>
{({ data, loading, error }) => {
if (loading || error) {
return null;
}
return <SubscriptionHandler data={data} />;
}}
</Subscription>
);
});
/*
* Component rendered when there's data from subscription
*/
const SubscriptionHandler = compose(
// This would be the query you want to refetch
lifecycle({
refetchQuery() {
// condition to refetch based on subscription data received
if (this.props.data) {
var variables = {
...this.props.data // if you need subscription data for the variables
};
// Fetch the query, will automatically update the cache
// and cause QueryComponent re-render
this.client.query(QUERY_GQL, {
variables: {
...variables
}
});
}
},
componentDidMount() {
this.refetchQuery();
},
componentDidUpdate() {
this.refetchQuery();
}
}),
renderNothing
)();
/*
* Component that creates the subscription operation
*/
const Subscriber = ({ username }) => {
return (
<Subscription
subscription={SUBSCRIPTION_GQL}
variables={{ ...variables }}
>
{({ data, loading, error }) => {
if (loading || error) {
return null;
}
return <SubscriptionHandler data={data} />;
}}
</Subscription>
);
});
Note:
compose and lifecycle are recompose methods that enable easier a cleaner higher order composition.

AngularJs directive templateURL in Laravel5.2

I want to use angular directive in my laravel project. But when I try to call my angular directive, tempateUrl of Angular Directive is not found. My Code is given below:
html
<demographich-url></demographich-url>
JS
.directive('demographichUrl', [function () {
return {
restrict: 'EA',
replace: true,
templateUrl: 'demographich', // this doesn't work
// 'templateUrl: './views/comments/comment-form.html', // this doesn't work
// 'templateUrl: './views/comments/comment-form.blade.php', // this doesn't work
// template:'<h1> hello world! </h1>', // this works
};
}])
Laravel Routes
// routes
Route::get('demographich', 'CompanyController#demographich');
// controller
public function demographich()
{
return view('comments.comment-form');
}
** comment-form.blade.php ( templateUrl page [ this page not found ] )**
<h1> Hi your comments goes here!!!! </h1>
** My file structure **
|
| --- resources
| --- views
| -- comments
| -- comment-form.blade.php
NB:
Laravel : 5.2
Angular: 1.5.X
I have solved this problem using below directive code.
.directive('demographichUrl', function () {
return {
restrict: 'EA',
scope: {
obj: '=',
submitFunc: '&'
},
templateUrl: '<?= asset('app/directive/demograph/demographich.html') ?>',
link: function (scope, iElement, iAttrs) {
}
};
})
You can use laravel blade page in directive..
.directive('surveyHeader', function () {
return {
restrict: 'EA',
scope: {
obj: '=',
submitSurveyheader: '&'
},
templateUrl: '<?php echo asset('app/directive/surveyheader/surveyheader.blade.php') ?>',
link: function (scope, iElement, iAttrs) {
}
};
})

Resources