1.

What are Relationships in Laravel?

Answer»

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.

<?phpnamespace App\Models;use Illuminate\Database\Eloquent\Model;class User extends Model{ /** * Get the phone associated with the user. */ public function phone() { return $this-&GT;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:

<?phpnamespace 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.



Discussion

No Comment Found