1 to many relationship in Laravel
class Post extends Model
{
// 1 Post has many comments
public function comments()
{
return $this->hasMany(Comment::class);
}
}
1 to many relationship in Laravel
class Post extends Model
{
// 1 Post has many comments
public function comments()
{
return $this->hasMany(Comment::class);
}
}
many to many relationship laravel
use App\Models\User;
$user = User::find(1);
$user->roles()->attach($roleId);
laravel many to many relationship
/*
users
id - integer
name - string
roles
id - integer
name - string
role_user
user_id - integer
role_id - integer
*/
class User extends Model
{
/**
* The roles that belong to the user.
*/
public function roles()
{
/*To determine the table name of the relationship's intermediate
table, Eloquent will join the two related model names in
alphabetical order. However, you are free to override this
convention. You may do so by passing a second argument to the
belongsToMany method*/
return $this->belongsToMany(Role::class,'role_user');
}
}
//Defining The Inverse Of The Relationship
class Role extends Model
{
/**
* The users that belong to the role.
*/
public function users()
{
return $this->belongsToMany(User::class);
}
}
Copyright © 2021 Codeinu
Forgot your account's password or having trouble logging into your Account? Don't worry, we'll help you to get back your account. Enter your email address and we'll send you a recovery link to reset your password. If you are experiencing problems resetting your password contact us