Laravel Eloquent Only Get One Row

Viewed 2102

So I want to show id from order table where user id is the same as currently login user id, then later used to show orders have been made by the user

$orderId = Order::select('id')->firstWhere('user_id', auth()->id())->id;

$orders = SubOrder::where('order_id', $orderId)->orderBy('created_at', 'desc')->get();

it works but it only shows the first record, after some digging later I found out that the problem is on the $orderId, it only shows the first record. but I want it to be all the records. if I change the id to get(), it shows nothing since it give the result like "id = 1" instead of the number only. also have tried to change the firstWhere into where and got error like "Property [id] does not exist on the Eloquent builder instance."
please help, thanks

2 Answers

If you are going to use the other Orders associated with the User soon after you get the first Order, return all the relevant Orders and then just grab the first one when you need it.

$orders = Order::where('user_id', auth()->user()->id)->get();

$firstOrder = $orders->first();

$subOrders = SubOrder::whereIn('order_id', $orders->pluck('id'))->get();

Alternatively, you could use a subOrders relationship defined on your Order model.

class Order extends Model
{
    public function subOrders()
    {
        return $this->hasMany(SubOrder::class);
    }
}
$orders = Order::where('user_id', auth()->user()->id)->get();

$firstOrder = $orders->first();

$firstOrderSubOrders = $firstOrder->subOrders;

If you're confident you're going to be working with SubOrder records, you can use eager loading on your Order to improve performance.

$orders = Order::where('user_id', auth()->user()->id)
    ->with('subOrders')
    ->get();

$firstOrder = $orders->first();

$firstOrderSubOrders = $firstOrder->subOrders;

first() will return the first id queried and stop execution.

$firstOrder = $orders->first();
Related