2017-08-24 83 views
1

我在Laravel 5.4和Vue公司JS 2個新的,我面對這個蒙山問題,我可以解決。Laravel 5/Vue公司JS:路線爲Get請求路由返回對象或數組取決於口才查詢

我有一個控制器2種方法(和路由關聯):

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, "amount": "10.00" }, { "id": 80, "id_booking": 3, "amount": "10.00" }, ....

這是我當我使用index_booking { "28": { "id": 29, "id_booking": 15, "amount": "45.00" }, "29": { "id": 30, "id_booking": 15, "amount": "48.00" } } 我卡住了!任何幫助將非常感激。乾杯

+0

'BookingPayment'是一個雄辯的模型嗎? –

+0

是的,它是!伊恩解決了我的問題。無論如何感謝 – leyom

回答

0

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(); 
} 
+0

這解決了我的問題。感謝您的幫助隊友! – leyom

+0

太棒了!任何時候! ps:答案爲+1 –