2017-07-23 31 views
-1

我想知道如何检查当前用户是否有任何订单?是否显示列表,如果不显示消息?如何检查laravel中的当前用户

我目前使用这一点,但它不能很好地工作:

@if (empty(Auth::user()->order)) 
     <blockquote> 
      <h1>Sorry you have no order at the moment, would you like to check out our products?</h1> 
      <footer><a href="{{route('shop')}}">Click here</a></footer> 
     </blockquote> 
     @else 
....... 

@endif 

用户模型:

public function order(){ 
     return $this->hasMany(Order::class); 
    } 

订货型号:

public function user(){ 
    return $this->belongsTo(User::class); 
    } 

我的控制器,显示订单历史查看:

public function index() 
    { 
     $user = Auth::user(); 
     $orders = Order::where("user_id", "=", $user->id)->orderby('id', 'desc')->paginate(10); 
     return view('users.orders', compact('user', 'orders')); 
    } 
+2

你能描述一下你的“它不能很好地工作”是什么意思?你的数据库的结构是什么?除此之外,从视图访问模型违反了MVC原则,在您的控制器中设置布尔值,表示存在或不存在订单。 –

+0

@DanielAlexandrov我的意思是它显示我的表,而不是显示文本(这是在我的代码中),当用户没有订单时,我想检查记录的用户ID与'订单'表,并且如果记录的用户ID匹配任何订单在订单表中显示他/她的订单清单中显示的文本中没有任何订单。 –

+1

您可以对订单进行计数:Auth :: user() - > orders-> count() –

回答

-1

可以使用数订单:

Auth::user()->orders->count() 
1

得到这个工作有几个先决条件:

  1. 有一个正确的DB模式
  2. relations设置(看来你需要one-to-many

如果你有这样的假设您关系设置为:

class User extends Model{ 
    /** 
    * Get the orders for the user 
    */ 
    public function orders(){ 
     return $this->hasMany('App\Order'); 
    } 
} 

您可以使用forelse刀片语法

@forelse (Auth::user()->orders as $order) 
    <li>{{ $order->title }}</li> 
@empty 
    <blockquote> 
     <h1>Sorry you have no order at the moment, would you like to check out our products?</h1> 
     <footer><a href="{{route('shop')}}">Click here</a></footer> 
    </blockquote> 
@endforelse 

这将创建一个for循环中,你可以声明HTML布局的订单。如果没有订单,则将使用empty块。

+0

不,它不会做ID! –

+0

@RobertNicjoo然后你还没有设置正确的关系,我想,你可以编辑你的原始问题,包括你的用户类 – milo526

+0

更新......... –

相关问题