Search code examples
phplaravelrelational-databaseone-to-manylaravel-8

Laravel 8: Trying to get property 'name' of non-object on One To Many Relationship


I'm using Laravel 8 to develop my project and in this project, I have applied OneToMany relationship between User Model and Role Model like this:

User.php:

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

Role.php:

public function users()
    {
        return $this->hasMany(Role::class);
    }

Now I want to edit users, so at edit.blade.php, I added this line for getting name of the role that the user has:

<option selected="selected">{{ $user->role->name }}</option>

Note that I have already compacted the user at edit Method:

public function edit(User $user)
    {
        return view('admin.users.edit', compact('user'));
    }

And currently all of the users have a role id.

But now I get this error:

Trying to get property 'name' of non-object (View: edit.blade.php)

So what is wrong here ? How can I get the name of role that user has ?

Here is also the Migration of roles table if you wanna look at it:

public function up()
    {
        Schema::create('roles', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('slug');
            $table->timestamps();
        });
    }

And this is add_fk_to_users_table Migration:

public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->unsignedBigInteger('role_id')->nullable()->unsigned();
            $table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
        });
    }

I would really appreciate any idea or suggestion from you guys about this...

Thanks in advance.


Solution

  • Your User.php should be like this:

    public function role()
    {
        return $this->belongsTo(Role::class);// <--- this was your mistake. "Role" is correct!
    }
    

    And Role.php:

    public function users()
    {
        return $this->hasMany(User::class); // <--- class should be "User" not "Role" here.
    }