Laravel Auth::user() pluck 奇怪的行为

huangapple go评论64阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年5月11日 03:43:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/76222075.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定