首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >尝试在null上读取属性"name“(View: C:\xampp\htdocs\Moja_OTT\resources\views\premium\profile.blade.php) )

尝试在null上读取属性"name“(View: C:\xampp\htdocs\Moja_OTT\resources\views\premium\profile.blade.php) )
EN

Stack Overflow用户
提问于 2022-07-01 03:04:57
回答 1查看 366关注 0票数 0

我想要一个简单的程序,显示登录后的用户配置文件。我使用了会话和中间件。但这意味着name属性为null。请帮我解决这个错误。我用过用户模型。属性的值不会从数据库中检索。

刀片代码:

代码语言:javascript
复制
<h1>Profile</h1>

<h2>Welcome Mr/Ms {{$user->name}}</h2>

<a href="{{route('logout')}}">Logout</a>

型号:

代码语言:javascript
复制
<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use App\Models\PremiumModel;

class User extends Authenticatable implements MustVerifyEmail
{
    use HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $table = 'users';
    protected $primaryKey = 'user_id'; 
    protected $timestamp = false;
    protected $fillable = [
        'name',
        'email',
        'password',
        'type',
        'email_verified_at',
        'pro_pic',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        
        'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
     
    function admin()
    {
        return $this->hasOne('App\Models\admin', 'user_id', 'admin_id');
    }
    function premium()
    {
        return $this->hasMany(PremiumModel::class, 'user_id', 'user_id');
    }
}

控制器代码:

代码语言:javascript
复制
function profile()
{
    $user = User::where('user_id',session()->get('logged'))->first();
    return view('premium.profile')->with('user',$user);
    
    
}

在这里,logged是中间件。

EN

回答 1

Stack Overflow用户

发布于 2022-07-01 05:34:28

您可以在用户模型中尝试hasOne

代码语言:javascript
复制
public function premium()
{
    return $this->hasOne(PremiumModel::class, 'user_id', 'user_id');
}

因为hasMany返回了一个数组,但是hasOne只返回了一个对象

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72823978

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档