尝试读取 属性 "name" on null in Laravel 8

Attempt to read property "name" on null in Laravel 8

我正在使用 laravel API 并使用模型关系和资源来获取数据,我不知道它给出这种错误的问题在哪里,我搜索并尝试了解决方案,但问题仍然存在。

这是我的控制器函数:-

 public function show(Question $question)
{
    return  new QuestionResource($question);
}

这是题型:-

class Question extends Model
{
use HasFactory;
protected $guarded = [];
public function getRouteKeyName()
{
    return 'slug'; 
}

public function user(){
    return $this->belongsTo (User::class, 'user_id');
}  
}

这是用户模型:-

public function question(){
    return $this->hasMany(\App\Models\Question::class);
}

这是 QuestionResource 函数:-

public function toArray($request)
{
    return [
        'title'=> $this->title,
        'slug'=>$this->slug,
        'body'=>$this->body,
        'created_at'=>$this->created_at->diffForHumans(),
        'updated_at'=>$this->updated_at->diffForHumans(),
        'user_name'=>$this->user->name,
    ];
}

这道题table:-

public function up()
{
    Schema::create('questions', function (Blueprint $table) {
        $table->increments('id');
        $table->string('title');
        $table->string('slug');
        $table->text('body');
        $table->integer('category_id')->unsigned();
        $table->integer('user_id')->unsigned();
        $table->timestamps();
    });
}

我相信解决方案在标题中 — 属性“名称”为 null。您很可能没有为问题模型分配用户,因此 $this->usernull

'user_name' => $this->user->name

您可以考虑先检查用户是否存在,如果不存在则设置默认值。

'user_name' => $this->user ? $this->user->name : ''