简体   繁体   中英

How to get data from database with Laravel back-end and Vue front end?

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.

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 (eg _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()
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM