【问题标题】:Put PHP data in HTML element将 PHP 数据放入 HTML 元素中
【发布时间】:2017-05-24 22:32:27
【问题描述】:

我想从函数执行的那一刻起(从用户登录的那一刻起)将经过身份验证的 $userId 作为 html 元素中的一个值,并将其放在 index.html 中的输入元素中

我的 AuthorizedAccessTokenController.php

class AuthorizedAccessTokenController
{
    public function getUser(Request $request)
    {
        //this is the key I want to place in my input
        $userId =  $request->user()->getKey();
        return $userId;
    }
}

这是我的 index.html 中的输入

<input type="text" value="the $userId">

【问题讨论】:

    标签: javascript php html ajax laravel


    【解决方案1】:

    要获得经过身份验证的用户 ID,您可以使用 id() 方法和 auth() 助手或 Auth 外观:

    <input type="text" value="{{ auth()->id() }}">
    

    或者:

    <input type="text" value="{{ Auth::id() }}">
    

    【讨论】:

    • 该方法不起作用,因此我需要以不同的方式进行。不使用 Auth::id()
    • @hxwtch 不起作用是什么意思?你得到一个错误或什么?您确定当前用户已通过身份验证吗?主键是users 表中的ID?这是一个普通的 Blade 文件还是你正在使用 JS 加载数据?
    • @AlexeyMezenin 请注意,如果您想在其中执行 PHP,则必须将您的 index.html 更改为 index.php
    • 它给出了错误:{error: "Unauthenticated."}。但是用户已登录。我什至使用 laravel Passport 登录用户并将其分配给令牌,但它仍然说它是“未经身份验证的”。
    【解决方案2】:

    echo '&lt;input type="text" value="' . $userid . '"&gt;';

    把它放在你获取用户 ID 的函数中

    【讨论】:

      【解决方案3】:

      在 PHP 中,您可以在字符串中的函数名称之前添加 $。这应该可以满足您的需求:

      <input type="text" value="$getUser($REQUESTVARIABLE)">
      

      这似乎是一个类的方法,所以你必须用你的对象实例正确调用它

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-02-25
        • 2019-06-28
        • 2022-01-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多