尝试在 Laravel 8 中读取 null 上的属性“name”

问题描述

我正在使用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,];
}

这是问题表:-

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();
    });
}

解决方法

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

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

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

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