首页 > 解决方案 > 尝试在 null 上读取属性“client_name”

问题描述

背景:我不熟悉 PHP,自从上一个开发人员离开后,我就一直在创建一个环境。

我的错误resources\views\layouts\app.blade.php

 <div class="user-wrapper">
            <img class="user-img" src="{{ asset('images/user-circle.svg')}}" alt="User"/>
            <div class="user-info">
              <h3>{{ Auth::user()->name}}</h3>
              <p> {{ Auth::user()->email}}</p>
              <p> {{ Auth::user()->client->client_name}}</p>
            </div>
          </div>

这是我的客户模型

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;


class Client extends Model
{
    use HasFactory;
    use SoftDeletes;

    protected $fillable = [
      'client_name',
      'description',
    ];
}

和用户模型

<?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;

class User extends Authenticatable
{
    use HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name',
        'email',
        'password',
        'client_id',
    ];

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

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    
    public function client(){
      return $this->hasOne(Client::class, 'id', 'client_id');
    }
}

我可以从我的数据库中获取名称和电子邮件,但对于客户端它以某种方式返回 null。我还验证了我可以从客户端表中获取数据。

编辑:我按照建议在客户端模型中添加了以下几行,但我仍然得到

 public function client(){
      return $this->hasOne(Client::class, 'client_id', 'id');
    }

标签: phplaravel-8

解决方案


我通过运行解决了这个问题:

php artisan migrate:reset
php artisan migrate

推荐阅读