skip to Main Content

I have a BelongsToMany relationship between Users and Products defined in the Nova Model:

BelongsToMany::make('Products'), //user has many products

The underlying models User and Athlete both have the relationship also:

//User.php
public function products()
{
    return $this->belongsToMany(Product::class);
}

//Product.php
public function users()
{
    return $this->belongsToMany(User::class);
}

When I try to update an attached product, the dropdown field is just disabled and I cannot change it.

Is this the default behaviour for BelongsToMany relations? AM I expected to remove the product and add the new (correct) one?


Update

Because nobody had any suggestion, I will assume that this is the default Laravel Nova Behaviour for BelongsToMany Relationships.

2

Answers


  1. Have you defined the relationship in your model? In your case I’d expect to have the following in your User model:

    public function products()
    {
        return $this->belongsToMany(Product::class);
    }
    

    Then in your User resource simply have the following:

    BelongsToMany::make('Products'),
    

    This should result in you having access to a select box of Products in your User resource, and no, them being greyed out is not default behaviour.

    If that’s what you currently have but you’re still getting this behaviour then post your code, otherwise it’s hard to help :).

    Login or Signup to reply.
  2. To update in a BelongsToMany relationship, you need to remove the old one and then attach the new one.

    $user = User::find($id); // get user
    $user->products()->detach($oldProductId);// remove old 
    $user->products()->attach($newProductId);// attach new
    

    Or you can use sync()

    $user->products()->sync([$newProductId]); // this will do both at once(remove and update)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search