英文:
Laravel Auth::user() pluck strange behavior
问题
以下是您要翻译的代码部分:
$items = Auth::user()->pluck('id');
结果:
Illuminate\Support\Collection 对象(
[items:protected] => 数组
(
[0] => 8
[1] => 5
[2] => 3
[3] => 7
[4] => 1
[5] => 9
...
)
[escapeWhenCastingToString:protected] => )
与期望的单个元素不同,此处显示了所有用户ID。有人能解释这是关于什么吗?
编辑:
为了更清晰:
$physicalExercises = Auth::user()
->with('physicalExercises')
->first()
->physicalExercises
->pluck('name', 'id');
和
$physicalExercises = User::where('id', Auth::id())
->with('physicalExercises')
->first()
->physicalExercises
->pluck('name', 'id');
有不同的结果。
英文:
$items = Auth::user()->pluck( 'id');
results
Illuminate\Support\Collection Object(
[items:protected] => Array
(
[0] => 8
[1] => 5
[2] => 3
[3] => 7
[4] => 1
[5] => 9
...
)
[escapeWhenCastingToString:protected] => )
with all user ids, Instead of the expected single element in the 'items' array.
Can anyone explain what this is about?
Edit:
for more clarity
$physicalExercises = Auth::user()
->with('physicalExercises')
->first()
->physicalExercises
->pluck('name', 'id');
and
$physicalExercises = User::where('id', Auth::id())
->with('physicalExercises')
->first()
->physicalExercises
->pluck('name', 'id');
Has a different result.
答案1
得分: 1
问题中的两个功能具有不同的行为。
// 检索当前已认证的用户...
$user = Auth::user();
// 检索当前已认证的用户的ID...
$id = Auth::id();
查看[认证文档](https://laravel.com/docs/10.x/authentication#retrieving-the-authenticated-user)了解更多信息。
附注:你可以使用`Auth::user()->id`的方式,但是简单地使用`Auth::id()`更清晰地访问ID。
英文:
Both function on question have different behavior.
// Retrieve the currently authenticated user...
$user = Auth::user();
// Retrieve the currently authenticated user's ID...
$id = Auth::id();
Check the authenticated docs for more info.
PS: You can do like Auth::user()->id
but simply do Auth::id()
, it's more cleaner to access the id.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论