Reputation: 3375
I'm trying something really simple and yet doesn't work. I have one controller where selecting from one database to show some info for user. Now I'm trying in this same controller to select from second table to show some other info but I get Undefined variable...
This is the part of controller which is problematic
public function orderView( $orderId, $userId ) {
$order = self::$user->orders()->where('order_id', $orderId)->first();
$keys = Keys::all();
if (!$order) {
App::abort(404);
}
$userID = $order['user_id'];
$orderID = $order['order_id'];
$public_key = $keys['public_key'];
$private_key = $keys['private_key'];
$options = array(
"public_key" => $public_key,
"private_key" => $private_key,
"orderID" => $orderID,
"userID" => $userID
);
What I have added here is
$keys = Keys::all();
$public_key = $keys['public_key'];
$private_key = $keys['private_key'];
....
"public_key" => $public_key,
"private_key" => $private_key,
The error is Undefined index: public_key
Upvotes: 0
Views: 136
Reputation: 3570
Keys::all()
returns an Illuminate\Database\Eloquent\Collection
.
In order to access a single item of the Collection, you either must iterate the collection and access them singularly, or take one item specifically with Collection's functions, such as first()
.
For example:
public function orderView($orderId, $userId)
{
$order = self::$user->orders()->where('order_id', $orderId)->first();
$keys = Keys::all();
if (! $order) {
App::abort(404);
}
$options = [];
foreach ($keys as $key)
{
$options[] = [
'public_key' => $key->public_key,
'private_key' => $key->private_key,
'userID' => $order->user_id,
'orderID' => $order->order_id
];
}
return $options;
}
You can find more information about Illuminate Collection methods here.
Upvotes: 2