Using a ManyToMany with additional Pivot fields - dedicated Model or not?

Posted 3 months ago by BarryJames

Hi I'm afraid I've complicated things and now I'm a little stuck, have read many articles but still cannot find the solution. So I have 2 resources - Users and Properties. It's a many to many as each owner can have many properties and each property can have many users.

My User Model:

class User extends Authenticatable
{
    public function properties()
    {
        return $this->belongsToMany(Property::class)->withPivot('type')->withTimestamps();
    }
}

My Property model:

class Property extends Model
{
    public function users()
    {
        return $this->belongsToMany(User::class)->withPivot('type')->withTimestamps();
    }
}

My pivot table:

class CreatePropertyUserTable extends Migration
{
    public function up()
    {
        Schema::create('property_user', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('user_id')->index();
            $table->unsignedInteger('property_id')->index();
            $table->string('type', 50);
            $table->timestamps();

            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->foreign('property_id')->references('id')->on('properties')->onDelete('cascade');
        });
    }
}

You can see from the above there is an additional field named 'Type' on the pivot table. This can be either 'Owner', 'Tenant', 'Agent'

Now when it comes to my Controller for showing the resource of the PropertyUsers, my route keeps track of the property and user, which means my controller also needs this with the edit function:

    public function edit(Property $property, User $user)
    {
        $user = User::whereHas('properties', function ($q) use ($property) {
            $q->where('id', $property->id);
        });

        return view('admin.propertyusers.edit')->withProperty($property)->withUser($user);
    }

This however doesn't work. I need the specific property user where the property equals that property and the user equals that user, then I need to show the 'type' field in the edit form so that I can change them to one of the other types if needed.

My problem is that no matter what I try the I cannot get the related table populated in my queries.

Also, it seems cumbersome to use a controller that needs two resources to compute queries and CRUD.

You see in normal OOP I used to create a single model of PropertyUser and use that, but now it seems I have to pull in a user and a property that isn't necessarily linked to each other. This is why I thought a dedicated model for this would help?

Any input would be greatly appreciated!

Cheers

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.