0

Good-day fellow Stackers

As a side project I am attempting to teach myself some basic full-stack development. It is a very interesting field and I would very much like to sharpen my skills.

My current task is simply to get data from a database through a back-end and then display it in the form of a table on a front-end. My chosen back-end is Laravel and I am using it in conjunction with Vue and Bootstrap-Vue for the front end part.

Below is my code in the HomeController.php file where I get all the database entries from the standard user table.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use \App\User

class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function index()
    {
        $users = User::all();
        return view('home', compact('users'));
    }
}

I then send these entries to the home.blade.php view which looks as follows:

@extends('layouts.app')

@section('content')
    <my-component></my-component>
@endsection

Here I want to pass the $users data to my Vue component (appropriately name my-component).

Inside my-component I want to display the names and emails in a table. I came across Bootstrap-Vue and I very much like the look of their components hence I would like to learn to use it, in this case I am using their table component (see my implementation below).

<template>
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <b-table
                :striped="striped"
                :bordered="bordered"
                :borderless="borderless"
                :outlined="outlined"
                :small="small"
                :hover="hover"
                :dark="dark"
                :fixed="fixed"
                :foot-clone="footClone"
                :no-border-collapse="noCollapse"
                :items="items"
                :fields="fields"
                :head-variant="headVariant"
                :table-variant="tableVariant"
                ></b-table>
            </div>
        </div>
    </div>
</template>

<script>
  export default {
    data() {
      return {
        fields: ['name', 'email', 'age'],
        items: [
          { age: 40, first_name: 'Dickerson', last_name: 'Macdonald' },
          { age: 21, first_name: 'Larsen', last_name: 'Shaw' },
          { age: 89, first_name: 'Geneva', last_name: 'Wilson' }
        ],
        tableVariants: [
          'primary',
          'secondary',
          'info',
          'danger',
          'warning',
          'success',
          'light',
          'dark'
        ],
        striped: true,
        bordered: false,
        borderless: false,
        outlined: false,
        small: false,
        hover: false,
        dark: false,
        fixed: false,
        footClone: false,
        headVariant: null,
        tableVariant: '',
        noCollapse: false
      }
    }
  }
</script>

However I am stuck at this point as to how do I pass the $users into the vue and replace the items: [ ... ] with my database data?

I realize that there are a lot of online tutorials that deal with this (CRUD tutorials) however most of these are in the form of "take this code and paste it in here" . As I am trying to learn it doesn't help I use someone else's code from a tutorial and in the process not know the how, when , where and what.

In my furious "how to googling" I came across the following question where a user experienced a similar problem. I followed the relevant links to read up on props from the Vue documentation however I am still at a loss as to how to do it.

Hence I ask of you, fellow Stackers, for your help/assistance/guidance/wisdom.

Edit:Most of my "googling" says I have to make use of an AJAX request, hence since I am using Laravel I know axios is the built-in tool for doing just that.

5
  • axios is the built-in tool - built in where? - have you read the vuejs example (cookbook) regarding how to use axios to consume API's? vuejs.org/v2/cookbook/using-axios-to-consume-apis.html Commented Dec 13, 2019 at 10:25
  • Well that is library that Laravel "ships" with for handling HTTP requests, perhaps my choice of vocab for "built-in" and "tool" is not entirely correct. Commented Dec 13, 2019 at 10:30
  • @JaromandaX No I have not looked at that link yet, however I see it contains a wealth of info, I will presently work through it! Thanks! Commented Dec 13, 2019 at 10:33
  • axios is a client side "library" for AJAX - anyway, that cookbook code should help Commented Dec 13, 2019 at 10:33
  • @JaromandaX axios is bundled with new Laravel projects when you create them with composer or with the laravel installer, along with Vue Commented Dec 14, 2019 at 3:41

1 Answer 1

1

quick and dirty

You can pass the data in JSON as a prop

<my-component :users='{{json_encode($users)}}'></my-component>
export default{
    props:['users']
}

the API way

Whenever I see Vue and Laravel, my thinking goes directly to SPA (Single page application). This is where all your web routes (/home, /users, etc.) Display only one view which is the application itself, then the application will get whatever data it needs through API calls to the server (/api/users, /api/posts)

In the above architecture, you would have a new method in your controller (e.g. _users()) which returns JSON data of all users, then your front can consume that data.

(You can also use this without making the whole thing an SPA)

_users(){ // resolve this in your routes.php as /api/users
    $users=Users::all()

    return $users; // Laravel will automagically cast toArray and json_encode
}
export default{
    data(){
        return{
            users:[]
        }
    },
    methods:{
        getUsers(){
            axios.get('/api/users')
            .then(response=>{
                this.users=response.data
            })
        }
    },
    mounted(){
        this.getUsers()
    }

}
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.