I'm doing get request using AJAX. In my Laravel Controller, I tried to use "->paginate(5);" and I got undefined values but when I'm using "->get();" it works perfectly but I wanted to use paginate to have pagination in my table. I think there is an issue on how I output the values. Get return an object and paginate return an array as per checking in console. I'm using this "$.each(response.data, function (key, item)" to output the values. Please help.
This is my controller
public function getOrders($store_id)
{
$data = DB::table('stores')
->where('stores.id',$store_id)
->paginate(5);
return response()->json(['data' => $data]);
}
This is my AJAX
function fetchOrder(){
$.ajax({
type: "GET",
url: "/get-orders/" store_id,
dataType: "json",
success: function (response) {
if (response.data != null) {
console.log(response);
$('.OrderTbody').html("");
$.each(response.data, function (key, item) {
$('.OrderTbody').append('<tr><td>' item.store_name '</td></tr>');
});
}
}
});
}
This is example output using paginate
This is the response in console using the get which is working
Object
data:
current_page: 1
data: [{…}]
first_page_url: "http://127.0.0.1:8000/get-orders/2?page=1"
from: 1
last_page: 1
last_page_url: "http://127.0.0.1:8000/get-orders/2?page=1"
links: (3) [{…}, {…}, {…}]
next_page_url: null
path: "http://127.0.0.1:8000/get-orders/2"
per_page: 15
prev_page_url: null
to: 1
total: 1
[[Prototype]]: Object
[[Prototype]]: Object
and this is response in console using paginate that is NOT WORKING
{data: Array(1)}
data: Array(1)
0:
address: "Cubao, Quezon City, Metro Manila, Philippines"
approval: 1
close_time: "20:24:00"
created_at: "2022-03-21 12:22:18"
id: 2
lat: "14.6177663"
lng: "121.0571541"
open_time: "20:23:00"
profile_image: "support-1store-prof_image1647868469.jpg"
status: 1
store_name: "Kainan"
store_users_id: 3
updated_at: "2022-03-21 13:14:29"
zipcode: "3112"
[[Prototype]]: Object
length: 1
[[Prototype]]: Array(0)
[[Prototype]]: Object
CodePudding user response:
Use
$.each(response.data.data, function (key, item) {
$('.OrderTbody').append('<tr><td>' item.store_name '</td></tr>');
});
CodePudding user response:
try importing your data like this :
$data = DB::table('stores')
->where('stores.id',$store_id)
->paginate(5)
->toArray();
adding ->toArray()
will simplify your objects so the JSON serialization will be more "easy" for the Laravel.