Laravel Relationships

Laravel Relationships

Defining Relationships

$user->posts()->where('active', 1)->get();

Defined as methods on your Eloquent model classes.

Querying Relations

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * Get all of the posts for the user.
     */
    public function posts()
    {
        return $this->hasMany('App\Post');
    }
}
$user = App\User::find(1);

$user->posts()->where('active', 1)->get();

Eager Loading

Alleviates the N + 1 query problem.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Book extends Model
{
    /**
     * Get the author that wrote the book.
     */
    public function author()
    {
        return $this->belongsTo('App\Author');
    }
}
$books = App\Book::all();

foreach ($books as $book) {
    echo $book->author->name;
}
$books = App\Book::with('author')->get();

foreach ($books as $book) {
    echo $book->author->name;
}
Select * from books

select * from authors where id in (1, 2, 3, 4, 5, ...)

Inserting & Updating Related Models

Touching Parent Timestamps

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Comment extends Model
{
    /**
     * All of the relationships to be touched.
     *
     * @var array
     */
    protected $touches = ['post'];

    /**
     * Get the post that the comment belongs to.
     */
    public function post()
    {
        return $this->belongsTo('App\Post');
    }
}
$comment = App\Comment::find(1);

$comment->text = 'Edit to this comment!';

$comment->save();

Laravel Relationships — Structure map

Clickable & Draggable!

Laravel Relationships — Related pages: