卡在laravel,试图将id存储在变量中

问题描述 投票:0回答:3

我想将配置文件表中的 user_id 存储到变量中。在我的索引函数中,我有:

$userid = Profile::where('user_id', auth()->user()->id)
            ->first();

        return view ('profile.index',[
            'user' => $user,
            'userid' => $userid,
          'about' => $about,

在我的索引视图中:

@if(Auth::user()->id == $userid)
        <h3>hello</h3>
     @endif

但是,我收到此错误:

App\Models\Profile 类的对象无法转换为 int (查看:C:\xampp\laravelprojects estfrihand 资源 iews\profile\index.blade.php)

php laravel
3个回答
2
投票

更改它以从模型实例获取

user_id

$userid = Profile::where('user_id', auth()->id)
            ->first()->user_id;

注意1:当你调用

first()
方法时,你将获得一个eloquent模型的实例。你应该告诉它你想要什么属性。在这里,您需要 user_id。
->first()->user_id
->first()->get('user_id')
都会给出您想要的答案。

注意2:您可以通过调用

auth()->id

获取当前已验证用户的ID

0
投票

实际上并不了解您到底需要什么。 但无论在哪里 $userid = Profile::where('user_id', auth()->user()->id) ->首先(); 这里你得到的是一个Profile对象,而不是一个id。 请具体说明您的问题:您想在此代码中存储 user_id,还是获取 user_id 并在条件下使用它?


-1
投票
$userid = Profile::where('user_id', auth()->user()->id)->first();

在这里你实际上并没有获得用户ID。您正在从用户模型中提取一行具有身份验证的用户。

return view ('profile.index',[
            'user' => $user,
            'userid' => $userid,
          'about' => $about,

本节中没有您作为用户发送的变量

我认为它正在尝试将任何模型(例如内容所有者 ID 等)中的

user id
与身份验证用户 ID 进行匹配。

这里有一些你可以使用的方法;

方法一:如果在代码的不同部分需要$user,可以将$user与ID列进行匹配。

$user = Profile::where('user_id', auth()->user()->id)->first();

return view ('profile.index',[
    'user' => $user,
    'about' => $about
];

然后;

@if(Auth::user()->id == $user->id)
    <h3>hello</h3>
@endif

方法2:如果代码中任何地方都不需要$user,而您只想检查用户;

$userId = Profile::where('user_id', auth()->user()->id)->first()->id;

return view ('profile.index',[
    'userId' => $userId,
    'about' => $about
];

然后;

@if(Auth::user()->id == $userId)
    <h3>hello</h3>
@endif

方法三:(推荐)可以使用Laravel授权。这使您可以轻松控制整个系统,并可以轻松地从一个地方控制所有授权

© www.soinside.com 2019 - 2024. All rights reserved.