A
A
Alexey Sklyarov2020-09-18 17:10:12
Laravel
Alexey Sklyarov, 2020-09-18 17:10:12

Why does the attach() method on the model not work?

Created two models Roles and Permissions. There is a set of permissions and a set of roles, and an associated roles_permissions table. One role can have many permissions, and one permission can have many roles.

I specify in the Role model:

Role.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Role extends Model
{
    use HasFactory;

    /**
     * Indicates if the model should be timestamped.
     *
     * @var bool
     */
    public $timestamps = false;

    public function permissions()
    {
        return $this->belongsToMany(Permission::class,'roles_permissions');
    }
}



Permission Model:
Permission.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Permission extends Model
{
    use HasFactory;

    /**
     * Indicates if the model should be timestamped.
     *
     * @var bool
     */
    public $timestamps = false;

    public function roles()
    {
        return $this->belongsToMany(Role::class,'roles_permissions');
    }
}



Data tables:
roles

+----+---------------+-------+
| id | name          | slug  |
+----+---------------+-------+
| 1  | Администратор | admin |
+----+---------------+-------+
| 2  | Пользователь  | user  |
+----+---------------+-------+


permissions

+----+------------+------------+
| id | name       | slug       |
+----+------------+------------+
| 1  | Edit users | edit_users |
+----+------------+------------+
| 2  | Edit posts | edit_posts |
+----+------------+------------+


roles_permissions

+---------+---------------+
| role_id | permission_id |
+---------+---------------+
| 1       | 1             |
+---------+---------------+
| 2       | 2             |
+---------+---------------+



I create a seeder, in it I specify:
Role::create([
        "name" => "Администратор",
        "slug" => "admin"
      ]);
and
$permission = Permission::create([
        "name" => "Редактировать пользователей",
        "slug" => "edit-users"
      ]);

      Role::where('slug','admin')->first()->attach($permission);


I start the seed and get an error: Call to undefined method App\Models\Role::attach()as far as I understand, this problem occurs if a many-to-many relationship is not set, but I have belongsTo everywhere. What could be the problem?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Ukolov, 2020-09-18
@0example

Role::where('slug','admin')->first()->permissions()->attach($permission);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question