Access Eloquent relationship in Vue.js

Published 2 months ago by laxsmi

Hello everybody,

I'm trying to achieve something that seems pretty simple, but I must be missing something.

I have a list of items in the database. I want to display a list of all items with Vue.js

So I have set up an "Items" component to do this:

<template>
<table class="table">

  <tr v-for='item in items' v-bind:key='item.id'>

    <td>{{ item.name }}</td>

    <td>{{ item.price }} €</td>

    <td>{{ item.status }}</td>

    <td>
  </tr>

</table>
</template>

and this components gets the list of items via an AJAX request when mounted:

<script>

     data() {
       return {
           items: {
               name: '',
               price: '',
               status: ''
           },
       }
     },

     mounted() {
       this.getAllItems();
     },

     methods: {
       getAllItems() {
         axios.get('/admin/get/')
           .then(response => {
             this.items = response.data.items;
           });
       },
   }

</script>

My controller is like this:

  public function getAllItems() {
    $items = Item::withTrashed()->with('status')->get();
    return response()->json([
      'items'    => $items
  ], 200);
  }

and everything works fine, but the {{ item.status }} part. This is an Eloquent relationship defined in my model:

  public function status() {
      return $this->trashed();
  }

and it works in PHP:

>>> $i = Item::find(12)->status();
=> false

but when called from Vue.js I get the following response with a 500 error: "Call to a member function addEagerConstraints() on boolean"

What I am doing wrong?

Best Answer (As Selected By laxsmi)
ouhare

First of all, your 'items' data should be an array :)

data () {
    return {
        items: []
    }
}

and then, you are trying to get a relationship with 'with' method but your status function is not a relationship !

take a look at : https://laravel.com/docs/5.6/eloquent-mutators#defining-an-accessor

ouhare

First of all, your 'items' data should be an array :)

data () {
    return {
        items: []
    }
}

and then, you are trying to get a relationship with 'with' method but your status function is not a relationship !

take a look at : https://laravel.com/docs/5.6/eloquent-mutators#defining-an-accessor

laxsmi

Wonderful!

So I defined the accessor and I added an appends attribute to my model to get it through Vue.js:

protected $appends = ['status'];

Thank you for your help ouhare!

ouhare

Glad to help !

Please sign in or create an account to participate in this conversation.