简体   繁体   English

Laravel 模型获取所有 $id = Auth::user()->id

[英]Laravel Model get all where $id = Auth::user()->id

How to List all rows from a DB where $id matches the logged user id.如何列出数据库中 $id 与记录的用户 ID 匹配的所有行。 I'm using default Auth from Laravel.我正在使用 Laravel 的默认 Auth。

At the moment i can list them all with this method in my controller:目前我可以在我的控制器中用这个方法列出它们:

public function index(){

    $invoices = Invoice::all();
    return view('index', compact('invoices'));
}

But i just want the ones that are from this user which is logged in:但我只想要来自这个登录用户的那些:

Something like就像是

$invoices = Invoice::where('id', '=', Auth::user()->id);

Your code Seems almost right. 您的代码似乎几乎正确。 I would do: 我会做:

$invoice = Invoice::where('id', Auth::user()->id)->get();

So basically use the get in order to fetch a collection. 因此,基本上使用get来获取集合。 And maybe I would separate the user id in a varaible in case that you change the authentication in the future ;) 如果将来您更改身份验证,也许我会把用户ID分开,以防万一;)

When using any condition then of course you must need to add the get() method.当使用任何条件时,当然你必须需要添加get()方法。 Otherwise, you can't show your data.否则,您无法显示您的数据。

$invoices = Invoice::where('id', '=', Auth::user()->id)->get();

This means that you want to see data on which user is logged in now这意味着您想查看有关当前登录用户的数据

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM