【问题标题】:Attempt to read property "name" on null in Laravel 8尝试在 Laravel 8 中读取 null 上的属性“名称”
【发布时间】:2021-08-08 07:25:32
【问题描述】:

我正在使用 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();
    });
}

【问题讨论】:

    标签: laravel laravel-8 laravel-api laravel-resource


    【解决方案1】:

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

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

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

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

    【讨论】:

      猜你喜欢
      • 2021-05-25
      • 2021-06-25
      • 2021-05-17
      • 2022-06-10
      • 2021-05-22
      • 2022-10-12
      • 2022-11-16
      • 2023-01-25
      • 2022-01-04
      相关资源
      最近更新 更多