0

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);
        }
Volka Dimitrev
  • 337
  • 4
  • 15
  • 38

3 Answers3

1

you can directly use count() of the collection class.

if($companies->count() > 0)

Use below code, when the relation is one-to-one

if($companies)
  • Not working, the same error occurring... – Volka Dimitrev Apr 19 '22 at 07:36
  • can you provide the relation code. – divyaraj ciesto Apr 19 '22 at 07:46
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Apr 19 '22 at 08:57
1

You can do it this way

https://laravel.com/docs/9.x/collections#method-isnotempty

$companies = $user->companies;

 if($companies->isNotEmpty()){ // check if records exists

  $getAuthUser_CompanyId = $companies->first()->id; // also update this line 

   //Logic
 }
Noman Saleem
  • 421
  • 1
  • 8
0

That is because a Collection is not an array.

getAuthUser_CompanyId = $companies->first()->id;