Search code examples
laravellaravel-8laravel-apilaravel-resource

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


I am working with laravel API and using model relationship and resource to get data, I don't know where is the problem that it gives such kind of error, I searched and tried the solutions, but the problem is still alive.

This is my controller function:-

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

This is the question model:-

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

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

This is the user model:-

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

And this is the QuestionResource function:-

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,
    ];
}

This is the question 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();
    });
}

Solution

  • I believe the solution is in the title — property "name" of null. You most likely do not have a user assigned to the Question model, so $this->user is null.

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

    You might consider checking that a user exists first and setting a default value if it does not.

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