Vue2 has been reading eloquent pretty well so far for me but except this point where I struggle to debug.
Shop-show.vue
<template>
.....
.....
<div class="row">
{{shop.user.id}}
</div>
.....
.....
</template>
<script>
export default{
mounted(){
this.getShop()
},
methods:{
getShop(){
var vm = this
vm.$http.get('/getShop/'+vm.shopId).then((response)=>{
vm.shop = response.data.data.shop
})
},
.....
.....
}
</script>
ShopController.php
.....
.....
public function getShop($id)
{
$shop = Shop::where('id',$id)->with('user')->firstOrFail();
$response = [
'data' => [
'shop' => $shop
]
];
return response()->json($response);
}
.....
.....
web.php
Route::get('/getShop/{id}', 'ShopController@getShop');
here when I render {{shop.user}} in my template it gives me perfectly fine object of user including info such as id and name, however when I do {{shop.user.id}} or {{shop.user.name}} it console log errors as followings
error#1
[Vue warn]: Error when rendering component at /Applications/XAMPP/xamppfiles/htdocs/soyegg/resources/assets/js/components/Shop/Shop-show.vue:
error#2
Uncaught TypeError: Cannot read property 'id' of undefined at Proxy.render (eval at (app.js:335), :46:47) at VueComponent.Vue._render (eval at (app.js:444), :3096:22) at VueComponent.eval (eval at (app.js:444), :2464:21) at Watcher.get (eval at (app.js:444), :1663:27) at new Watcher (eval at (app.js:444), :1655:12) at VueComponent.Vue._mount (eval at (app.js:444), :2463:19) at VueComponent.Vue$3.$mount (eval at (app.js:444), :6104:15) at VueComponent.Vue$3.$mount (eval at (app.js:444), :8494:16) at init (eval at (app.js:444), :2777:11) at createComponent (eval at (app.js:444), :4120:9)
this has never happened before, very weird. Please help.
As you are loading vm.shop from getShop method, which is an async method, you will not have anything in vm.shop till it is populated, so initially you will get this error.
To prevent this error, you can put a null check before using it, with the help of v-if, like following:
<template>
.....
.....
<div class="row" v-if="shop && shop.user">
{{shop.user.id}}
</div>
.....
.....
</template>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With