PHP Array Undefined Index Error After Converting JSON-ThrowExceptions

Exception or error:

I’m messing a little with PHP arrays and JSON, and when I was trying to “develop” a middleware to control the user access to certain pages of my system this error showed up:

Undefined index: access

This is a sample of my code;

$arrKey = "company_id";
$id = 1;
$json = '{"access":[{"company_id":1,"role_id":3}, {"company_id":2,"role_id":4}]}';
$array = (array)json_decode($json, true);
/*
This is the array from the JSON
Array
(
    [access] => Array
        (
            [0] => Array
                (
                    [company_id] => 1
                    [role_id] => 3
                )

            [1] => Array
                (
                    [company_id] => 2
                    [role_id] => 4
                )

        )

)
*/
foreach ($array['access'] as $key => $val) {
   if ($val[$arrKey] == $id) {
       return $key;
   }
}

I’ve even tried some work around with something like this

$array = (array)json_decode($json, true);
$array = $array['access'};

But the same error showed again.
For more information, I’m using Laravel 6, my PHP version is 7.3.9, and here is my entire code:

<?php

namespace App\Http\Middleware;

use Request;
use Closure;
use App\Models\Role;
use Route;

class CheckRole
{
    public function getRoute()
    {
        if(is_numeric(Request::segment(1)))
            return Request::segment(2);
        return Request::segment(2);
    }

    public function getRoleId()
    {
        return Request::user()->id;
    }

    public function getRole()
    {
        /*
            Request::user()->companies return:
            {
                "access":[
                    {
                    "company_id":1,
                    "role_id":3
                    },
                    {
                    "company_id":2,
                    "role_id":4
                    }
                ]
            }
        */
        return $this->searchForId($this->getCompanyId(), Request::user()->companies, 'company_id');
    }

    public function getCompanyId()
    {
        return Request::segment(1);
    }

    public function searchForId($id, $json, $arrKey) {
        $array = (array)json_decode($json, true);
        foreach ($array['access'] as $key => $val) {
            if ($val[$arrKey] == $id) {
                return true;
            }
        }
        return false;
    }

    public function checkAccess()
    {
        if(is_numeric(Request::segment(1)))
        {
            return $this->searchForId($this->getRoleId(), $this->getRole(), "company_id");
        }
        return true;
    }
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if(!$this->checkAccess())
        {    
            return redirect("/");
        }
        return $next($request);
    }
}

The code isn’t complete yet, after this error started to show up, I stopped everything to (try to) solve this error, and I’m almost replacing “JSON” for “serialize”, I tested it and worked just fine but I think it isn’t the best option because maybe in the future I’m going to re-create all my project with Python/NodeJS API and ReactJS to consume it, and JSON would be the best option.

How to solve:

Leave a Reply

Your email address will not be published. Required fields are marked *