php 控制器中的 Laravel Auth 用户 ID

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31575854/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 22:31:53  来源:igfitidea点击:

Laravel Auth user id in controller

phplaravellaravel-5

提问by Joe

I am using the Laravel boilerplate. I'm trying to get the user_idof the signed in user. I am getting the following error:

我正在使用 Laravel 样板。我正在尝试获取user_id已登录用户的 。我收到以下错误:

Class 'App\Http\Controllers\Frontend\Auth' not found

找不到类“App\Http\Controllers\Frontend\Auth”

Here is the call

这是电话

$user = Auth::user();

Then I try to get the id using:

然后我尝试使用以下方法获取 id:

$user->id

What am I missing?

我错过了什么?

回答by Ammadu

You need to use the Auth facade in the controller;

您需要在控制器中使用 Auth 门面;

add this line just before class definition.

在类定义之前添加这一行。

use Auth;

回答by Kavinda Prabhath

Try this,

尝试这个,

auth()->user()->id;

When you try to get the user by using $user = Auth::user();Laravel tries to load Auth class from the current location. In your case, it is

当您尝试使用$user = Auth::user();Laravel获取用户时,会尝试从当前位置加载 Auth 类。在你的情况下,它是

'App\Http\Controllers\Frontend'

'应用\Http\控制器\前端'

So Laravel is looking for Auth class inside the Frontend directory, which is not in. That's why you got that error message saying not found as below,

所以 Laravel 正在寻找 Frontend 目录中的 Auth 类,它不在。这就是为什么你收到错误消息说找不到如下,

'Class 'App\Http\Controllers\Frontend\Auth' not found'

'找不到类'App\Http\Controllers\Frontend\Auth'

If you use use Auth;method, you have to type use Auth;in each and every controller that you are going to use the Auth controller.

如果使用use Auth;方法,则必须输入use Auth;要使用 Auth 控制器的每个控制器。

Instead of typing use Auth;in each and every controller you can simply use the Laravel helper function as auth()->user().

而不是输入的use Auth;在每一个控制器,你可以简单地使用Laravel的辅助功能auth()->user()

from that you can get any value from the db like:

从中您可以从数据库中获取任何值,例如:

auth()->user()->id

auth()->user()->f_name

回答by Karthik

Add the following line before the Class definition

在类定义之前添加以下行

use Auth;

Get your current user id using the following code:

使用以下代码获取您当前的用户 ID:

$currentuserid = Auth::user()->id;