Relation Basics

Most scenarios are covered by a hasOne, hasMany or ManyToMany relation. How to use them is explained in detail here. I give a brief overview how they are connected to the database.

User hasOne Phone

You should have two tables that look somehow like this:

User Table
id name
1 Bob
Phone Table
user_id phone
1 1234567

From the user class you can access his phone as


 return $this->hasOne('App\Phone','user_id','id');   

And you can go back from your phone class to the related user:


     return $this->belongsTo('App\User','user_id','id');

User hasMany Phones

Since a user may have multiple phones, one needs to equip each phone with an unique id.

User Table
id name
1 Bob
Phone Table
id user_id phone
1 1 1234567
2 1 7654321

From the user class we only need to change hasOne to hasMany


return $this->hasMany('App\Phone','user_id','id');

In the phone class we do not need to make any changes.


return $this->belongsTo('App\User','user_id','id');

User hasMany Phones & Phone hasMany Users

In this scenario we need a pivot table

User Table
id name
1 Bob
2 Alice
Phone Table
id phone
1 1234567
2 7654321
User_Phone Table
user_id phone_id
1 1
1 2
2 2

Now both directions (back or forth) are pretty much the same and look like this in the user class:


     $this->belongsToMany('App\Phone','user_phone','user_id', 'phone_id');

and in the phone class:


    $this->belongsToMany('App\User','user_phone','phone_id','user_id');
adam