<?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);
}
}
?>
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.