and94es's avatar

"Trying to access array offset on value of type null", exception: "ErrorException"

I'm using Laravel witch Vuejs, present the following condition which goes through the categories, the daughter categories and the products. The conditional works, but when displaying the data of the query it gives me the error of: Trying to access array offset on value of type null

The error gives me in: ->paginate($request['pagination']['per_page'], ['*'], 'page', $pagination['page']);

this my function

function getProductsStore(Request $request)
{

    $active_categories = [];

    if(optional($request['query'] ??null)['active']!==null) {
        $active_categories = $this->findChildren($request['query']['active']);
    }

    if (!empty($active_categories)) {
        $categories = Category::whereIn('category_id', $active_categories)
            ->with('childrenRecursive')
            ->withCount('products', 'children')
            ->get();
    } else {
        $categories = Category::with('childrenRecursive')
            ->withCount('products', 'children')
            ->whereNull('category_id')
            ->get();
    }
    
    Log::info('in getprods');
    Log::info(print_r($active_categories, true));

    $pagination = $request->query('pagination');
    $prod = Product::where('is_active', true)
        ->with(['categories', 'brand', 'images' => function ($query) {
            $query->where('default', true);
        }])
        ->Order($request)
        ->BrandStore($request)
        ->CategoryStore($request, $active_categories)
        ->paginate($request['pagination']['per_page'], ['*'], 'page', $pagination['page']);


    return response()->json([
        "products" => $prod->toArray()['data'],
        "categories" => $categories,
        "page" => $prod->currentPage(),
        "pages" => $prod->lastPage(),
        "per_page" => $request['pagination']['per_page'],
        "total" => $prod->total(),
        "sort" => "asc",
        "field" => "product",
    ]);
}
0 likes
5 replies
SilenceBringer's avatar

@and94es so, 2 possibilities:

  1. $request['pagination'] is null
  2. $pagination is null

just dd it

$pagination = $request->query('pagination');
dd($request['pagination'], $pagination);
and94es's avatar

The result is :

  1. $request['pagination'] is []
  2. $pagination is null
SilenceBringer's avatar

@and94es

$pagination = $request->pagination;
dd($pagination);

if it has correct values - use it. Otherwise specify default values

->paginate(Arr::get($pagination, 'per_page', 60), ['*'], 'page', Arr::get($pagination, 'page', 1))
and94es's avatar

$pagination = $request->pagination; dd($pagination);

Result is:

array:4 [ "page" => 1 "pages" => 0 "per_page" => 5 "total" => 0 ]

SilenceBringer's avatar
Level 55

@and94es so, use this

->paginate($pagination['per_page']), ['*'], 'page', $pagination['page']))

and it should works

1 like

Please or to participate in this conversation.