Showing orders of user in laravel

◇◆丶佛笑我妖孽 提交于 2019-12-12 03:02:29

问题


I'm trying to give ability on user to see his orders. How can I query the database.. I'm trying something like this but I got empty page.. I mean nothing from database. May be my query ins't correct.

This is my controller

public function viewOrders() {
    $user_order = self::$user->user_id;
    $orders = Order::where('user_id', '=', $user_order);
    return View::make('site.users.orders', [
        'orders' => $orders
    ]);
}

Am I getting correctly user_id here? I'm not sure...

Update: I have this in my User model

public function orders() {
    return $this->hasMany('Order', 'user_id', 'user_id');
}

回答1:


Ok, so based on your route+button+model do it like this

$orders = self::$user->orders()->orderBy('order_id', 'asc')->get();
return View::make('site.users.orders', [
    'orders' => $orders
]);

this should work.. You can remove orderBy clause if you don't need it.




回答2:


If you have Authentication set properly you can do the following.

public function viewOrders(){
    $user = Auth::user();
    return view('site.users.orders',[
        'orders' => $user->orders
    ]);
}

When you use the relationship without using the calling parentheses you get a collection of models which are queried if they're not already loaded. This is called lazy loading, if you want to load a relationship before accessing it you can use eager loading. In this case, it is not necessary though.



来源:https://stackoverflow.com/questions/37874771/showing-orders-of-user-in-laravel

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!