NEOJPK
NEOJPK

Reputation: 833

Laravel is not defined

Well i am playing with the new laravel 5.3 and vue.js and i want to do a GET call to some users i have in my DB

Im using components btw.

This is my app.js

require('./bootstrap');

Vue.component('example', require('./components/UserComponents/User.vue'));

const app = new Vue({

    el: 'body',

});

This is my component User.vue i left the HTML template out for post size reason i can post it if neccesary

<script>

    export default{

        data : function () {
            return {
                users : ''
            }
        },

        methods: {


            fetchUser: function () {

                var vm = this;

                vm.$http.get('user/', function (data) {
                   vm.$set('users', data)
                })

            }
        },
        ready() {

            this.fetchUser();
        },

    }
</script>

Im getting 2 errors in the console

 vue-resource.common.js?d39b:27 0ReferenceError: Laravel is not defined(…)

(program):29 Uncaught (in promise) ReferenceError: Laravel is not defined(…)

this is my package.json as you can see i have all the deps for this to work vue and vue resource

{
  "private": true,
  "scripts": {
    "prod": "gulp --production",
    "dev": "gulp watch"
  },
  "devDependencies": {
    "bootstrap-sass": "^3.3.7",
    "gulp": "^3.9.1",
    "jquery": "^3.1.0",
    "laravel-elixir": "^6.0.0-9",
    "laravel-elixir-vue": "^0.1.4",
    "laravel-elixir-webpack-official": "^1.0.2",
    "lodash": "^4.14.0",
    "vue": "^1.0.26",
    "vue-resource": "^0.9.3"
  }
}

Hope someone could help me out here. Thank you

Upvotes: 16

Views: 12383

Answers (3)

omarjebari
omarjebari

Reputation: 5519

if you're using axios then ensure the following is in your bootstrap.js file after axios is imported:

window.axios.defaults.headers.common = {
    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
    'X-Requested-With': 'XMLHttpRequest'
};

Upvotes: 0

Mihai Ocneanu
Mihai Ocneanu

Reputation: 797

Or for a cleaner format:

<script>
    window.Laravel = { csrfToken: '{{ csrf_token() }}' };
</script>

Does same thing as Rocco's answer.

Upvotes: 40

Rocco Milluzzo
Rocco Milluzzo

Reputation: 1007

Try to put this on your blade, as you can see is inserted by default on app.blade on Laravel 5.3

<script>
    window.Laravel = <?php echo json_encode([
        'csrfToken' => csrf_token(),
    ]); ?>
</script>

Upvotes: 39

Related Questions