Dexx
Dexx

Reputation: 163

laravel ->get() not returning relations properly

I have a conditional query that works in my index controller that should return eloquent relationships but does not always return an accessible array index:

$customers = Customer::with('orders', 'regions')->orderBy('created_at', 'desc')->whereHas('regions', function($query)
    {
        $user_id = Auth::user()->id;
        $current_user = User::with('roles')->where('id', '=', $user_id)->latest()->first();
        $role_name = $current_user->roles[0]->name;
        if($role_name == 'admin_master'){$query->whereIn('region', array(11, 7));}
    }
    )->get(); 

The problem is the related array is not always accessible eg order[1] and displays oddly when I dd($customers);

#relations: array:5 [▼
    "orders" => Collection {#442 ▼
      #items: array:2 [▼
        0 => Order {#446 ▶}
        1 => Order {#447 …25}
      ]
    }

Upvotes: 0

Views: 328

Answers (1)

Arun Code
Arun Code

Reputation: 1638

For future users, the get method gets the results as a collection. You can chain the toArray() method on it to convert it into an array.

So it will be something like $query->get()->toArray()

Upvotes: 1

Related Questions