In my laravel application some of the users can have a assigned company and some don't have a assigned company.
But both type of users can update their details to the system.
If it is a user who has a company, then I'm checking his company id is a valid one or not.
If the user doesn't have an assigned company, I don't need to check that..
In order to do that I have following in my controller,
$companies = $user->companies;
This $companies will basically contains an collection like below,
Illuminate\Database\Eloquent\Collection {#2770
  #items: array:1 [
    0 => App\Company {#2778
      #connection: "mysql"
      #table: "companies"
      #primaryKey: "id"
      #keyType: "int"
      +incrementing: true
      #with: []
      #withCount: []
      +preventsLazyLoading: false
      #perPage: 15
      +exists: true
      +wasRecentlyCreated: false
      #escapeWhenCastingToString: false
      #attributes: array:25 [
        "id" => 635
        "uuid" => "283c18b514"
        "name" => "apple"
        "email" => "ceo@apple.co"
        "phone_number" => "6149297830"
        "website" => "https://www.apple.co"
        "country_id" => 232
        "state" => "California"
        "postal_code" => ""
        "house_number" => ""
        "street" => ""
        "city" => "Menlo Park"
        "chamber_of_commerce" => null
        "vat_number" => null
        "lat" => 37.4529598
        ....
Now I'm trying run some codes if this $companies is NOT empty. which means, the user has already assigned company.
if(!empty($companies)){
            $getAuthUser_CompanyId = $companies[0]->id;
            $employeeID_ExistsCompany= CompanyUser::whereExists(function ($query) use ($getAuthUser_CompanyId,$employee_Id) {
                $query->select(DB::raw(1))
                    ->from('users')
                    ->where('company_user.user_id', '=',$employee_Id)
                    ->where('company_id', '=', $getAuthUser_CompanyId);
            })
            ->get();
            if(!$employeeID_ExistsCompany)
            abort(403);
        }
Now the issue is,
When I try to run this It kept giving me an error saying,
message: "Undefined array key 0"
How can I properly check if this $companies not empty? Where should I fix?
Update
Tried using
if($companies->isNotEmpty())
Since am using laravel 9, but still getting the same exception...
if($companies->isNotEmpty())
        {
            $getAuthUser_CompanyId = $companies->first()->id;
            $employeeID_ExistsCompany= CompanyUser::whereExists(function ($query) use ($getAuthUser_CompanyId,$employee_Id) {
                $query->select(DB::raw(1))
                    ->from('users')
                    ->where('company_user.user_id', '=',$employee_Id)
                    ->where('company_id', '=', $getAuthUser_CompanyId);
            })
            ->get();
            if(!$employeeID_ExistsCompany)
            abort(403);
        }
 
     
     
    