Reputation: 7628
I am creating a front-end Vue component. For this I am using data and a database from a Laravel project. The problem I got is that a method from Laravel (And so does the AJAX call) is returning an Array, which is good, and the other method is returning just the objects (collection?) with the AJAX call. I need both calls returning an Array because I am using some Array functions in my component.
I've tried all sort of things, both on the front-end as back-end. I've tried on the backend to let laravel return an array and on the Front-end I tried to set the objects to an array. Both didn't succeed.
My JS code (And AJAX calls)
methods: {
countAllItems() {
this.countItems = this.items.length;
},
getUrl(items) {
let results = items;
results.forEach((item) => {
let id = item.id;
return item.url = `/advertisements/show/${id}`;
});
},
getMax(items) {
let boats = items.slice(0, 4);
this.items = boats;
this.getUrl(this.items);
this.countAllItems();
},
getBoats() {
axios.get('/api/boats')
.then((response) => {
//this will return an array
console.log(response.data);
this.items = response.data;
this.countAllItems();
this.getMax(this.items);
})
.catch((error) => console.log(error));
},
getReservations() {
axios.get('/api/popular')
.then((response) => {
//this will return objects, and must be an array
console.log(response.data);
this.items = response.data;
this.countAllItems();
this.getMax(this.items);
});
}
},
created() {
this.getBoats();
this.getReservations();
}
The back-end
//This will return the array
public function boats() {
return Boat::with('media')->get();
}
//This will return objects
public function messages() {
$boats = Boat::with('media')->get()->sortByDesc(function($boat) {
return count($boat->conversations);
});
return $boats;
}
Is there someone who can help me out? So I need either a fix for returning an array in the Laravel method, or something like a function to push both objects to an array in JavaScript.
Edit
So I tried some things and doing that something occured to me. When I do dd($boats)
it will return a Collection. When I do dd($boats->toArray)
it returns an array. What the weird thing is is that it makes no difference tho in the AJAX calls. So $boats->toArray()
will still return only the objects and not the objects in an array.
I also tried to push the objects in an array but that doesn't work either. It will place the collection (as a object) into an array. How can I change this that the objects will directly be inserted in the array instead of the collection as a object?
let arr = [];
arr.push(response.data);
console.log(arr);
Upvotes: 0
Views: 962
Reputation: 1539
I think problem with collection manipulation, When you do collection manipulation, it changes the values.
public function messages() {
$boats = Boat::with('media')->get();
$sorted = $boats->sortByDesc('do your sort here');
return $sorted->values();
}
Upvotes: 1