javascript - Laravel 5/VueJS : Route for Get request route return Object or Array depending Eloquent query

标签 javascript arrays laravel object vuejs2

我是 Laravel 5.4 和 Vue js 2 的新手,我遇到了这个我可以解决的问题。

我有一个带有 2 种方法(以及关联的路由)的 Controller :

public function index()
{
    //
    return BookingPayment::all();
}

public function index_booking($id_booking)
{
    return BookingPayment::all()
        ->where('id_booking', '=', $id_booking)
        ->toArray(); // <<-- no effects !?
}

方法index返回表中的所有行,index_booking执行过滤器id_booking字段。

在 php 我的 PHP 页面中,我有一个 javascript,它对这两个路由执行请求。 我的问题是当我使用 index_booking 时,请求返回一个对象。我期望一个数组,因为我将能够轻松地使用数组函数来操作结果。

这是我的 JavaScript :

var vm = new Vue({

el: '#bookingpay',

data: function () {
    return {
        booking_id: 15,
        payments: [],
        input: [{id: 0, id_booking: 0, new_amount: 99}]
    }
},

mounted: function () {
    this.fetchPayment();
},

methods: {

    fetchPayment: function () {
        this.$http.get('/api/bookingpayments_bybooking/' + this.booking_id).then(function (response) {
            this.payments = response.data;
        })
    },

    delPayment: function (id, index) {
        this.$http.delete('/api/bookingpayments/' + id).then(function () {
            this.payments.splice(index, 1); // doesn't work on Ojbect
        })
    },

    addPayment: function () {
        this.$http.post('/api/bookingpayments', this.input).then(function () {
            this.payments.push(this.input);
        })
    },

}

});

这是我期望的 http 查询响应格式。这就是我使用索引时所拥有的: [ { “ID”:79, “id_booking”:3, “金额”:“10.00” }, { “id”:80, “id_booking”:3, “金额”:“10.00” }, ....

这是我使用 index_booking 时得到的: { “28”:{ “ID”:29, “id_booking”:15, “金额”:“45.00” }, “29”:{ “id”:30, “id_booking”:15, “金额”:“48.00” } } 我被困住了!任何帮助将不胜感激。干杯

最佳答案

您的index_booking 错误。正确的做法是:

public function index_booking($id_booking)
{
    // This will return a Collection that will be translated to an array/json when you hit the endpoint via ajax. There is no need for toArray(), though...
    return BookingPayment::where('id_booking', '=', $id_booking)->get();
}

关于javascript - Laravel 5/VueJS : Route for Get request route return Object or Array depending Eloquent query,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45858857/

相关文章:

javascript - 在框架内题写和居中图像

ios - 循环字典数组中的元素

c - 逐行读取字符串数组中的内容

javascript - Laravel 分页将问题与设计联系起来

php - Laravel Maatwebsite/Laravel-Excel 更新(如果存在)

php - 安装 Laravel 所需的最低 php 版本

javascript - 我的 jQuery slider 无法正常工作

javascript - 排除项目及其内容元素

java - 验证项目是否在开始日期和结束日期内

javascript - Vue 在 Axios API 调用中将 bool 从 true 更改为 false