;

Laravel Eloquent relationship cheat sheet

Andy Haxby

21 July 2020

When I started using Laravel, I loved how easy it was to resolve relationships, but i always kept forgetting which methods I should use for which relationship. So in this blog post I’d like to put together a cheat sheet that can be used to quickly figure out how to properly define the 3 most common relationship types.

Defining Relationships

Lets quickly go over on how to define a relationship again. They are defined as functions in the appropriate model. For example:

    public function posts() {
        return $this->hasMany('App\Post', 'user_id');
    }

A relationship can be resolved by calling the method on the instance of the model by running $user->posts or $user->posts(). Keep in mind that both of these methods return a different result. Calling the relationship as a property will return a collection of models. Calling it as method will return an instance of the corresponding relation object. This can be used whenever you want to for example add a where constraint to the query that retrieves the relational data or it can be used to associate data with each other. In every example also specifies which holds the ID (or foreign key). The model that holds the ID normally need to use the belongsTo method (reverse relationship). For any of the information of the parameter i’ll link to the appropriate section in the Laravel documentation.

One To One

In the following example the Phone model holds the User ID.

Relationship declaration

User.php
    public function phone() {
        return $this->hasOne('App\Phone');
    }

A Phone can be associated to User using:

    $user->phone()->save( $phone );

Reverse relationship declaration

Phone.php
    public function user() {
        return $this->belongsTo('App\User');
    }

A User can be associated to Phone using:

    $phone->user()->associate( $user );
Laravel Eloquent: One to One

Back-end

Laravel

PHP

Credits

Andy Haxby

Founder

Andy is the founder of Competa and FTSF. He is always looking to find ways to improve sustainability with software.

Related articles

The latest articles on business and tech information.