0

For the past few days, I have been following a tutorial about VUE application from a really good youtuber. I was following each and every step as it was mentioned in the tutorial when suddenly I have come to an abrupt halt. This is because the data from my database is not showing up in the frontend. The database does show that I am storing the data properly, and there are no errors whatsoever. The video where I got stuck on is: https://youtu.be/bUXhGw4aQtA

Here is the code for the index in my controller

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

Here is the app.js

/**
 * First we will load all of this project's JavaScript dependencies which
 * includes Vue and other libraries. It is a great starting point when
 * building robust, powerful web applications using Vue and Laravel.
 */

require('./bootstrap');

window.Vue = require('vue');
import {
  Form,
  HasError,
  AlertError
} from 'vform'

window.Form = Form;
Vue.component(HasError.name, HasError)
Vue.component(AlertError.name, AlertError)

import VueRouter from 'vue-router'
Vue.use(VueRouter)

let routes = [{
    path: '/dashboard',
    component: require('./components/Dashboard.vue').default
  },
  {
    path: '/profile',
    component: require('./components/Profile.vue').default
  },
  {
    path: '/users',
    component: require('./components/Users.vue').default
  }
]

const router = new VueRouter({
  mode: 'history',
  routes // short for `routes: routes`
})

/**
 * The following block of code may be used to automatically register your
 * Vue components. It will recursively scan this directory for the Vue
 * components and automatically register them with their "basename".
 *
 * Eg. ./components/ExampleComponent.vue -> <example-component></example-component>
 */

// const files = require.context('./', true, /\.vue$/i);
// files.keys().map(key => Vue.component(key.split('/').pop().split('.')[0], files(key).default));

Vue.component('example-component', require('./components/ExampleComponent.vue').default);

/**
 * Next, we will create a fresh Vue application instance and attach it to
 * the page. Then, you may begin adding components to this application
 * or customize the JavaScript scaffolding to fit your unique needs.
 */

const app = new Vue({
  el: '#app',
  router
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<template>
    <div class="container">
           <div class="row mt-5">
          <div class="col-md-12">
            <div class="card">
              <div class="card-header">
                <h3 class="card-title">Users Table</h3>

                <div class="card-tools">
                    <button class="btn btn-success" data-toggle="modal" data-target="#addNew">Add new <i class="fas fa-user-plus"></i></button>
                </div>
              </div>
              <!-- /.card-header -->
              <div class="card-body table-responsive p-0">
                <table class="table table-hover">
                  <tbody>
                    <tr>
                        <th>ID</th>
                        <th>Name</th>
                        <th>Email</th>
                        <th>Type</th>
                        <th>Registered At</th>
                        <th>Modify</th>
                  </tr>


                  <tr v-for="user in users.data" :key="user.id">


                    <td>{{user.id}}</td>
                    <td>{{user.name}}</td>
                    <td>{{user.email}}</td>
                    <td>{{user.type | upText}}</td>
                    <td>{{user.created_at | myDate}}</td>

                    <td>
                          <a href="#" >
                              <i class="fa fa-edit blue"></i>
                          </a>
                          /
                          <a href="#">
                              <i class="fa fa-trash red"></i>
                          </a>
                      </td>
                    </tr>
                </tbody>
                </table>                  
              </div>
            </div>
            <!-- /.card -->
          </div>
        </div>
        <!-- Modal -->
        <div class="modal fade" id="addNew" tabindex="-1" role="dialog" aria-labelledby="addNewLabel" aria-hidden="true">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="addNewLabel">Add Users</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                    </button> 
                </div>
                <form @submit.prevent="createUser">
                <div class="modal-body">
                    <div class="form-group">
                      <input v-model="form.name" type="text" name="name"
                        placeholder="Name"
                        class="form-control" :class="{ 'is-invalid': form.errors.has('name') }">
                      <has-error :form="form" field="name"></has-error>
                    </div>

                    <div class="form-group">
                      <input v-model="form.email" type="text" name="email"
                        placeholder="email"
                        class="form-control" :class="{ 'is-invalid': form.errors.has('email') }">
                      <has-error :form="form" field="email"></has-error>
                    </div>

                    <div class="form-group">
                      <textarea v-model="form.bio" type="text" name="bio"
                        placeholder="Bio"
                        class="form-control" :class="{ 'is-invalid': form.errors.has('bio') }"></textarea>
                      <has-error :form="form" field="bio"></has-error>
                    </div>

                    <div class="form-group">
                      <select v-model="form.type" type="text" name="type"
                        class="form-control" :class="{ 'is-invalid': form.errors.has('type') }">
                        <option value="">Select user Role</option>
                        <option value="user">Employee</option>
                        <option value="manager">Manager</option>
                      </select>
                      <has-error :form="form" field="name"></has-error>
                    </div>

                    <div class="form-group">
                      <input v-model="form.password" type="password" name="password"
                        placeholder="password"
                        class="form-control" :class="{ 'is-invalid': form.errors.has('password') }">
                      <has-error :form="form" field="password"></has-error>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                    <button type="submit" class="btn btn-primary">Create</button>
                </div>

                </form>
                </div>
            </div>
            </div>            
    </div>
</template>

<script>
  export default {
    data() {
      return {
        users: {},
        form: new Form({
          name: '',
          email: '',
          password: '',
          type: '',
          bio: '',
          photo: '',
        })
      }
    },
    methods: {
      loadUsers() {
        axios.get("api/user").then(({
          data
        }) => (this.user = data));
      },
      createUser() {
        this.form.post('api/user');
      }
    },
    created() {
      this.loadUsers();
    }
  }
</script>

Please let me know if any other code is required for me to elaborate on the query that I have here. I have tried all options that I could think of and search and couldn't get it to work. Hopefully, another set of eyes can help me figure out the problem.

I expect a full table showing all the rows from my database, and the front-end shows nothing. (Note: I did check the network tab in the developer's options in Chrome and there was only a single xhr type and it showed status 200).

3
  • Why not use developer tool to console.log result of your API call in the method for a start.That way you can be sure the front end receives the data from the backend Commented Jun 14, 2019 at 22:49
  • I would need a bit of an assistance with that because I am new to all this vue and API thing Commented Jun 14, 2019 at 23:10
  • Your user in the data should be an array, not object. Your axios call in your loadusers() function is wrong and then while iterating, its not ~user in users.data~ but ~user in users~. Check my modified answers. Commented Jun 15, 2019 at 7:21

2 Answers 2

1

I suggest you go on youtube to search for laravel/vue tutorials, there are tons of good resources there that can help you. For what you are trying to achieve, if you have mounted your component well and can see a dummy test in the component on your browser, then you are half way done. Inside your mounted hook of your vue component, make an api call to your backend (laravel) to fetch users like so;

axios.get('/get_all_users').then((res)=>{
  this.users = res.data
  //do a console.log(res.data) to ensure you are getting the users collection
}).catch((err) => {
  console.log(err)
});

Inside your data object, create an empty array that holds your users like so;

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

Now, inside your web.php, create a GET route for this api call;

ROUTE::get('/get_all_users', 'UsersController@FetchUsers');

Note that your controller and method necessarily not be named as above, create a controller, and inside, write a method to fetch users and use them here asap; Inside your controller, write your method;

public function FetchUsers(){
  $users = User::latest()->get();
  return response()->json($users, 200);
}

Also note that you will need to import your User model at the top of the controller file like so;

use App\User;

Also ensure before now that you have the User model created that relates to your users table; By now you should see the arrays of users on your browser developer tool console if everything is fine. Then in your template, iterate through the users data like so;

<tr v-for="user in users" :key="user.id">
  <td>{{ user.id }} </td>
  <td>{{ user.name }} </td>
  <td>{{ user.email }} </td>
  <td>{{ user.created_at }} </td>
</tr>

I will be glad to help in case you need further clarifications.

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

Comments

1

You need to return your data as json. You can use Laravel [Resource] (https://laravel.com/docs/5.8/eloquent-resources)

Create user resource

php artisan make:resource User

User Controller

use App\Http\Resources\User as UserResource;

On your Method

$user = User::latest()->paginate(10);
return UserResource::collection($user)

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.