Answers for "many to many relationship laravel example"

PHP
5

many to many relationship laravel

// in User model:
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * The roles that belong to the user.
     */
    public function roles()
    {
        return $this->belongsToMany('App\Role');
    }
}

// in Role model:
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Role extends Model
{
    /**
     * The users that belong to the role.
     */
    public function users()
    {
        return $this->belongsToMany('App\User')->using('App\UserRole');
    }
}
Posted by: Guest on October-13-2021
7

belongs to many laravel

For example, a blog post may have an infinite number of comments. And a single
comment belongs to only a single post  

class Post extends Model
{
    public function comments()
    {
        return $this->hasMany('App\Models\Comment');
    }
}

class Comment extends Model
{
    public function post()
    {
        return $this->belongsTo('App\Models\Post');
    }
}
Posted by: Guest on October-16-2020
1

laravel one to many relationship example

$user->roles()->attach($roleIds);
$user->roles()->detach($roleIds);
$user->roles()->sync($roleIds);
$user->roles()->toggle($roleIds);
Posted by: Guest on September-13-2021
0

1 to many relationship in Laravel

class Post extends Model
{
   // 1 Post has many comments
    public function comments()
    {
        return $this->hasMany(Comment::class);
    }
}
Posted by: Guest on July-18-2021
1

many to many relationship laravel

use App\Models\User;

$user = User::find(1);

$user->roles()->attach($roleId);
Posted by: Guest on February-13-2021
0

many to many relationship laravel example

<?php namespace App; use Illuminate\Database\Eloquent\Model; class UserRole extends Model{     }
Posted by: Guest on July-27-2021

Code answers related to "many to many relationship laravel example"

Browse Popular Code Answers by Language