Laravel 8: Trying to get property 'name' of non-object

Viewed 1880

I'm making a forum with Laravel 8. And I want to return a question and show the name of the user who has asked this question.

At the Model User.php I coded this:

public function questions()
    {
        return $this->hasMany(Question::class);
    }

And also I put this at Question.php Model:

public function users()
    {
        return $this->belongsTo(User::class);
    }

So in order to get the name of a user who has asked the question, I put this:

{{ $show->users->name }}

But now I get this error message:

Trying to get property 'name' of non-object**

So what's going wrong here? How can I fix this issue?

Note that this $show variable comes from this Controller Method and gets the question information:

public function showQuestion($slug)
    {
        $show = Question::where('slug', $slug)->first();

        if(is_null($show)){
            abort(404);
        }

        return view('questions.question',[
            'show' => $show
        ]);
    }

And also each question has stored the user_id of the user who has asked this question:

capture

So if you have any idea or suggestion on this, please let me know, I would really appreciate that!

Update #1:

Here is the table users:

enter image description here

Update #2:

questions table migration:

Schema::create('questions', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('user_id');
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->string('title');
            $table->string('slug');
            $table->text('body');
            $table->string('category');
            $table->string('private')->nullable();
            $table->timestamps();
        });

users table migration:

public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('phone')->unique();
            $table->binary('image')->nullable();
            $table->string('job')->nullable();
            $table->string('location')->nullable();
            $table->string('bio')->nullable();
            $table->string('skills')->nullable();
            $table->string('stackoverflow')->nullable();
            $table->string('github')->nullable();
            $table->string('instagram')->nullable();
            $table->string('linkedin')->nullable();
            $table->string('website')->nullable();
            $table->rememberToken();
            $table->timestamps();
        });
    }
4 Answers

You have to change the function name users to user in Question model. when you are letting Eloquent automatically figure out the relationship you have to name the function regarding to their relationships like one to one or one to many or many to many.

Try this

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


{{ $show->user->name }}

Your relationship on Question to User should be named user instead of users. When you are letting Eloquent automatically figure out the fields for the belongsTo relationship it actually uses the name of the relationship method to help determine what the foreign key is.

If you don't want to follow that type of convention with naming the method like that you can explicitly set the foreign key used by the belongsTo method:

public function belongsTo($related, $foreignKey = null, $ownerKey = null, $relation = null)

Use this for show function in controller $student= Student::all(); return view('showData',['data' => $student]);

and for view to show data @foreach($data as $stud) <tr> <td>{{$stud)->id}}</td> <td>{{$stud)->name}}</td> </tr> @endforeach

return $this->belongsTo(User::class);

switch to like this, I switched to hasOne and it worked well

return $this->hasOne(User::class, 'id', 'user_id')
  ->withDefault(['name' => '']);
Related