Laravel 5: Eloquent – relationship types: one to one

Eloquent: relationship types – one to one

DB tables used in examples: here.

one2one

One-to-one:
One user has one phone and one phone belongs to one user.
ONE user has ONE phone: hasOne()
base notation

explanation:

  • method location – this method goes into parent Model – User in this case
  • argument #1 – Phone: this is child object name
    it can be given as:

    • object name with path: App\Models\Phone
    • object name: Phone – required use App\Models\Phone
    • class name: Phone::class  – required use App\Models\Phone
  • argument #2foreign_key relation
    what is foreign key: column in table ‘phones’ used to relate to table ‘users’, in other words: holding user table main id
    this is optional, if foreign key name is a snake case of parent model name and suffix ‘_id’, in this case: user_id
    if your foreign_key name is different, you have to state it as argument #2
  • argument #3 – local_key relation
    what is local_key: it is primary key in users (parent model) table
    Laravel expects it to be named id, if it is not, local_key must be given in hasOne method
how it looks like – example:

Inverse: ONE phone belongs to ONE user: belongsTo()
base notation

explanation:

  • method location – this method goes into child Model – Phone in this case
  • argument #1 – User: this is parent object name
    it can be given as:

    • object name with path: App\Models\User
    • object name: User – required use App\Models\User
    • class name: User::class  – required use App\Models\User
  • argument #2foreign_key relation
    what is foreign key: column in table ‘phones’ used to relate to table ‘users’, in other words: holding user table main id
    this is optional, if foreign key name is a snake case of parent model name and suffix ‘_id’, in this case: user_id
    if your foreign_key name is different, you have to state it as argument #2
  • argument #3 – other_key relation (equivalent to local_key in hasOne)
    what is other_key: it is primary key in users (parent model) table
    Laravel expects it to be named id, if it is not, other_key must be given in belongsTo method
how it looks like – example:

how to use it
Access data via User object.
We can use Eloquent dynamic property.

Access data via Phone object.
We can use Eloquent dynamic property.