Relationships in Laravel are a way to define relations between different models in the applications. It is the same as relations in relational databases.
Different relationships available in Laravel are:
- One to One
- One to Many
- Many to Many
- Has One Through
- Has Many Through
- One to One (Polymorphic)
- One to Many (Polymorphic)
Many to Many (Polymorphic)
Relationships are defined as a method on the model class. An example of One to One relation is shown below.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* Get the phone associated with the user.
*/
public function phone()
{
return $this->hasOne(Phone::class);
}
}
The above method phone on the User model can be called like : `$user->phone` or `$user->phone()->where(...)->get()`.
We can also define One to Many relationships like below:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* Get the addresses for the User.
*/
public function addresses()
{
return $this->hasMany(Address::class);
}
}
Since a user can have multiple addresses, we can define a One to Many relations between the User and Address model. Now if we call `$user->addresses`, eloquent will make the join between tables and it will return the result.