【问题标题】:how to get specific item just from user id to show at view如何仅从用户 ID 获取特定项目以显示在视图中
【发布时间】:2017-10-05 09:17:01
【问题描述】:

这是我当前的代码

    $products=Product::all();
    return view('user.products.index', compact('products'));

此代码将所有产品返回到视图。
如何仅将登录用户上传的产品返回到视图?

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    如果你已经通过外键建立了用户表和产品表的关系,或者你正在保存链接用户的产品和他的id,可以这样显示-

    use Auth;
    Product::where('user_id', Auth::id())->get();
    

    或者如果你正在使用守卫,那么以这种方式调用--

    use Auth;
    Product::where('user_id', Auth::guard('guard_name')->id())->get();
    

    它将返回与登录用户关联的所有产品的数组。

    【讨论】:

      【解决方案2】:

      您可以使用where()

      Product::where('user_id', auth()->id)->get();
      

      或者通过使用关系:

      auth()->user()->products()->get();
      

      或者你可以使用延迟加载:

      auth()->user()->load('products');
      

      【讨论】:

        猜你喜欢
        • 2015-01-22
        • 1970-01-01
        • 1970-01-01
        • 2020-12-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-03-20
        相关资源
        最近更新 更多