Skip to content

Instantly share code, notes, and snippets.

@nissicreative
Last active May 20, 2021 02:18
Show Gist options
  • Save nissicreative/71be3e362fed75edccb3bb38486db28b to your computer and use it in GitHub Desktop.
Save nissicreative/71be3e362fed75edccb3bb38486db28b to your computer and use it in GitHub Desktop.
Laravel Relationship Methods

Laravel Eloquent Relationships

One To One

Class User

/**
 * Get the phone record associated with the user.
 */
public function phone()
{
    return $this->hasOne('App\Phone', '[foreign_key]', '[local_key]');
}

Class Phone

/**
 * Get the user that owns the phone.
 */
public function user()
{
    return $this->belongsTo('App\User', '[foreign_key]', '[other_key]');
}

One To Many

Class Post

/**
 * Get the comments for the blog post.
 */
public function comments()
{
    return $this->hasMany('App\Comment', '[foreign_key]', '[local_key]');
}

Class Comment

/**
 * Get the post that owns the comment.
 */
public function post()
{
    return $this->belongsTo('App\Post', '[foreign_key]', '[other_key]');
}

Many To Many

Class User

/**
 * The roles that belong to the user.
 */
public function roles()
{
    return $this->belongsToMany('App\Role', '[role_user]', '[user_id]', '[role_id]');
}

Class Role

/**
 * The users that belong to the role.
 */
public function users()
{
    return $this->belongsToMany('App\User')
        ->withPivot('column1', 'column2')
        ->withTimestamps();
}

Has Many Through

Class Country

/**
 * Get all of the posts for the country.
 */
public function posts()
{
    return $this->hasManyThrough(
        'App\Post', 'App\User', '[country_id]', '[user_id]', '[id]'
    );
}

Polymorphic Relations

posts
    id - integer
    title - string
    body - text

videos
    id - integer
    title - string
    url - string

comments
    id - integer
    body - text
    commentable_id - integer
    commentable_type - string

Class Comment

/**
 * Get all of the owning commentable models.
 */
public function commentable()
{
    return $this->morphTo();
}

Class Post, Video

/**
 * Get all of the post's comments.
 */
public function comments()
{
    return $this->morphMany('App\Comment', 'commentable');
}

Many To Many Polymorphic Relations

posts
    id - integer
    name - string

videos
    id - integer
    name - string

tags
    id - integer
    name - string

taggables
    tag_id - integer
    taggable_id - integer
    taggable_type - string

Class Post

/**
 * Get all of the tags for the post.
 */
public function tags()
{
    return $this->morphToMany('App\Tag', 'taggable');
}

Class Tag

/**
 * Get all of the posts that are assigned this tag.
 */
public function posts()
{
    return $this->morphedByMany('App\Post', 'taggable');
}

/**
 * Get all of the videos that are assigned this tag.
 */
public function videos()
{
    return $this->morphedByMany('App\Video', 'taggable');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment