Answers for "many to many relationship laravel"

PHP
4

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

one 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
4

whereHas site:https://laravel.com/docs/

use Illuminate\Database\Eloquent\Builder;

// Retrieve posts with at least one comment containing words like code%...
$posts = Post::whereHas('comments', function (Builder $query) {
    $query->where('content', 'like', 'code%');
})->get();

// Retrieve posts with at least ten comments containing words like code%...
$posts = Post::whereHas('comments', function (Builder $query) {
    $query->where('content', 'like', 'code%');
}, '>=', 10)->get();
Posted by: Guest on December-17-2020
5

laravel detach

// Detach a single role from the user...
$user->roles()->detach($roleId);

// Detach all roles from the user...
$user->roles()->detach();
Posted by: Guest on September-15-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
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

Code answers related to "many to many relationship laravel"

Browse Popular Code Answers by Language