+1 vote
in Laravel by
What are Relationships in Laravel?

1 Answer

0 votes
by

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:

  1. One to One
  2. One to Many
  3. Many to Many
  4. Has One Through
  5. Has Many Through
  6. One to One (Polymorphic)
  7. 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.

Related questions

0 votes
asked Oct 22, 2023 in Laravel by john ganales
0 votes
asked Oct 17, 2023 in Laravel by Robindeniel
+1 vote
+1 vote
asked Jun 27, 2023 in Laravel by SakshiSharma
0 votes
asked Jun 27, 2023 in Laravel by Robindeniel
...