1
votes

Please i try to make a many to many relationship in Laravel 5.4 but i allways get this error:

BadMethodCallException in Builder.php line 2443: Call to undefined method Illuminate\Database\Query\Builder::categories()

I think my code is fine , and i can't fix it , any help please.

THank you.

THis is my code :

User model

class User extends Model
{
    public function categories()
    {
        return $this->belongsToMany('App\Category', 'user_categorys');
    }

}

Category model

class Category extends Model
{

    public function users()
    {
        return $this->belongsToMany('App\User', 'user_categorys');
    }

}

Call method

$user = User::where('id',$id_user)->first();
            foreach ($request->input("idcategs") as $value) {
                $user->categories()->save($value);
            }
2
This error is saying you're calling categories() on a query builder, not the model. Are you confident you have $users assigned from a first() call in your code?Devon

2 Answers

1
votes

You should use attach(), detach() and sync() methods when using many to many relationship to attach or detach models.

If idcategs is an array of IDs, do something like:

$user = User::find($id_user);
$user->attach($request->idcategs);

If it's an array of prepared data, you'll need to create categories first:

$categoriesIds = [];
$user = User::find($id_user);
foreach ($request->idcategs as $value) {
    $categoriesIds[] = Category::create($value)->id;
}
$user->attach($categoriesIds);

https://laravel.com/docs/5.4/eloquent-relationships#updating-many-to-many-relationships

-1
votes

You get it wrong: If you have a Many to Many relationship one or your relation should be:

public function users()
    {
        return $this->belongsToMany('App\User', 'foreign_key');
    }

and you will have to define a pivot table category_user