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

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

}

Leave a comment