如何在 laravel 中查看当前用户

How to check current user in 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'));
    }

要实现此功能,需要满足一些先决条件:

  1. 拥有正确的数据库模式
  2. relations setup (it seems you need one-to-many

如果你有这个并假设你的关系设置为:

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

您可以使用 forelse blade 语法

@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 块。

您可以使用以下方法计算订单:

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