Answer the question
In order to leave comments, you need to log in
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:
<?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');
}
}
<?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');
}
}
+----+---------------+-------+
| id | name | slug |
+----+---------------+-------+
| 1 | Администратор | admin |
+----+---------------+-------+
| 2 | Пользователь | user |
+----+---------------+-------+
+----+------------+------------+
| id | name | slug |
+----+------------+------------+
| 1 | Edit users | edit_users |
+----+------------+------------+
| 2 | Edit posts | edit_posts |
+----+------------+------------+
+---------+---------------+
| role_id | permission_id |
+---------+---------------+
| 1 | 1 |
+---------+---------------+
| 2 | 2 |
+---------+---------------+
Role::create([
"name" => "Администратор",
"slug" => "admin"
]);
and$permission = Permission::create([
"name" => "Редактировать пользователей",
"slug" => "edit-users"
]);
Role::where('slug','admin')->first()->attach($permission);
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
Role::where('slug','admin')->first()->permissions()->attach($permission);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question