pagination with vue + laravel

Viewed 145

In controller:

public function index(Request $request, $id) {
    if (!empty($id)) {
        $product = product::select('name', 'price', 'quantity')
            ->where('id', $id)
            ->get()->toArray();
        return response()->json($product);
    }
}

In Vue, I use Axios to get data.

axios
    .get("/api/product", {
        params: {
          id: id,
        },
    })
    .then((res) => {
        this.rows = res.data;
    })
    .catch((error) => {
        console.log(error);
    });

It shows the list okay But I want it not to get all the data..but by pagination, one-click on pagination it will load 30 items. Give me ideas, thanks.

1 Answers

I used to like this.

In controller :

public function index(Request $request, $id)
    {
            if (!empty($id)) {
                $currentPage = $request->input('currentPage', 1);
                $pageSize = $request->input('pageSize', 30);
                $skip = ($currentPage - 1) * $pageSize;

                $product = product::select('name', 'price', 'quantity')
                    ->where('id', $id)
                    ->skip($skip)
                    ->take($pageSize)
                    ->get()->toArray();
                return response()->json($product);
            }
    }

custom helper function in Vue

function object2query(obj) {
  let query = "?";
  let tempArray = [];
  for (let key in obj) {
    let value = obj[key];
    if(value) tempArray.push(`${key}=${value}`);
  }
  query += tempArray.join('&');
  return query;
}

In vue axios to get data.


let id = 5; // example id;
let pageSize = 30; // example page size;
let currentPage = 2; // example current page;

axios
      .get(`/api/product${object2query({
          currentPage,
          pageSize
        })}`, {
        params: {
          id
        },
      })
      .then((res) => {
        this.rows = res.data;
      })
      .catch((error) => {
        console.log(error);
      });
Related