微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决尝试在 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 : ''

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。