2

I want to display the user name instead supervisor_id in the table list in Vue.js. this is one to many relationship. supervisor_id is foreign key from user table.

/// this is view in vue.js. I want to to change work.supervisor_id into something like work.user.name, but it do not work.

<tr v-for="(work,index) in works.data" :key="work.work_id">
                <td>{{index+1}}</td>
                <td>{{work.work_name}}</td>
                <td>{{work.supervisor_id}}</td>  
                <td>{{work.payment}}</td>
                <td>{{work.created_at | myDate}}</td>
                <td>{{work.end_date}}</td>
                <td>{{work.worker_id}}</td> 
                <td>

/// this is my script in vue.js

<script>
export default {
  data() {
    return{
      editmode: false,
      works:{},
      index:1,
      users:{},
      form: new Form({
        work_id:'',
        work_name:'',
        description:'',
        payment:'',
        location:'',
        end_date:'',
        worker_id:'',
        application_status:'New',
        supervisor_id:'',
                   })
    }
  },

  methods:{

    getResults(page = 1) {
            axios.get('api/work?page=' + page)
              .then(response => {
                this.works = response.data;
      });
    },


    loadWork(){
      if(this.$gate.isClerk()){
       // axios.get('api/work').then(({data})=>(this.works = data));
       axios.get('api/work').then(response => (this.works = response.data));
      }
    },

/// this is my work controller

public function index()
{
    return Work::latest()->paginate(10);
}

the data in the vue.js devtool

2
  • Hi Mohd, please reduce your question at the maximum around your problem, and be clear with indented code etc. Thanks you Commented May 24, 2019 at 8:34
  • i have updated my question. Hope you can help Commented May 24, 2019 at 8:52

1 Answer 1

6

For this to work, it would require the a relationship on the Work model which returns the supervisor record which you require.

This will allow you to get the supervisor's (or user's depending on the relationship) name.

Work Model (app\Work.php):

public function supervisor()
{
    return $this->hasOne(User::class, 'supervisor_id');
}

Now in your controller, you can use the ->with() eloquent method to eager load a relation:

public function index()
{
    return Work::with('supervisor')->latest()->paginate(10);
}

You should now be able to access the supervisor name within vue using:

{{ work.supervisor.name }}

I hope this helps.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.