SPONSORS

266 views · 25 days ago

![Laravel Eloquent Relationship Part 1](https://images.ctfassets.net/vzl5fkwyme3u/2iNUlfYJ8SZVYUSemRAszt/eeb78994b12f1491f654d77026ab6c33/AdobeStock_199075029.png?w=1000)

Laravel introduces eloquent relationships from laravel 5.0 onwards. We all know, while we creating an application we all have foreign keys. Each table will be connected to some other. Eloquent make easy to connect each tables easily. Here we will One to one, one to many and many to many relationships. Here we will see three types of relationships,

1. One to one relationships

2. One to many relationships

3. Many to many relationships

## Why Eloquent Relationships

Here we have 2 tables, students and marks, so for join each table,

```php

$student = student::join(‘marks’,’marks.student_id,’=’,students.id’)->where(‘students.id’,’1’)->get();

dd($student);

```

the above query is to long, so when we connect more tables its too tough we will be having a big query and complicated.

## Model Query using Relationships

```php

$student_marks = student::find(1);

dd($student_marks->mark1);

```

The above example is a simple example of eloquent relationships. We can reduce the first query into a simple one.

### ONE TO ONE RELATIOSHIPS

Here we are creating 2 tables:

* Users

* Phones

Now we can see one to one relationships using `hasone()` and `belongsto()`.

We need to create table using migrations

#### Create migrations

users table will be created by using

```

Schema::create('users', function (Blueprint $table) {

$table->increments('id');

$table->string('name');

$table->string('email')->unique();

$table->string('password');

$table->rememberToken();

$table->timestamps();

});

```

Phones table will be created by

```

Schema::create('phones', function (Blueprint $table) {

$table->increments('id');

$table->integer('user_id')->unsigned();

$table->string('phone');

$table->timestamps();

$table->foreign('user_id')->references('id')->on('users')

->onDelete('cascade');

});

```

After that we need to create model for each tables, as we all know if the table name is laravel table name will be ending with ‘s’ and model name will be without ‘s’ of the same table name.

#### User model

```php

<?php

namespace App;

use Illuminate\Notifications\Notifiable;

use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable

{

use Notifiable;

protected $fillable = [

'name', 'email', 'password',

];

protected $hidden = [

'password', 'remember_token',

];

public function phone()

{

return $this->hasOne('App\Phone');

}

}

```

#### Phone Model

```php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Phone extends Model

{

/ **

* Get the user that owns the phone.

*/

public function user()

{

return $this->belongsTo('App\User');

}

}

```

#### For Creating records

```php

$user = User::find(1);

$phone = new Phone;

$phone->phone = '9080054945';

$user->phone()->save($phone);

$phone = Phone::find(1);

$user = User::find(10);

$phone->user()->associate($user)->save();

```

Now we can get our records by

```php

$phone = User::find(1)->phone;

dd($phone);

$user = Phone::find(1)->user;

dd($user);

```

### ONE TO MANY RELATIONSHIPS

Here we will use `hasMany()` and `belongsTo()` for relationships

Now we are creating two tables, posts and comments, we will be having a foreign key towards posts table.

Migrations for posts and comments table

```

Schema::create('posts', function (Blueprint $table) {

$table->increments('id');

$table->string("name");

$table->timestamps();

});

Schema::create('comments', function (Blueprint $table) {

$table->increments('id');

$table->integer('post_id')->unsigned();

$table->string("comment");

$table->timestamps();

$table->foreign('post_id')->references('id')->on('posts')

->onDelete('cascade');

});

```

Now we will create Post Model and Comment Model

#### Post Model

```php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model

{

public function comments()

{

return $this->hasMany(Comment::class);

}

}

```

#### Comment Model

```php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Comment extends Model

{

public function post()

{

return $this->belongsTo(Post::class);

}

}

```

Now we can create records

```php

$post = Post::find(1);

$comment = new Comment;

$comment->comment = "Hi Harikrishnan";

$post = $post->comments()->save($comment);

$post = Post::find(1);

$comment1 = new Comment;

$comment1->comment = "How are You?";

$comment2 = new Comment;

$comment2->comment = "Where are you?";

$post = $post->comments()->saveMany([$comment1, $comment2]);

$comment = Comment::find(1);

$post = Post::find(2);

$comment->post()->associate($post)->save();

```

Now we can get records

```php

$post = Post::find(1);

$comments = $post->comments;

dd($comments);

$comment = Comment::find(1);

$post = $comment->post;

dd($post);

```

### MANY TO MANY RELATIONSHIPS

Many to many is little bit different and complicated than the above two.

In this example, I will create users, roles, and role, users_tables, here each table will be connected each other using the foreign keys.

Using `belongsToMany()` we will use see a demo of Many to many relationship

#### Create Migrations

```

Schema::create('users', function (Blueprint $table) {

$table->increments('id');

$table->string('name');

$table->string('email')->unique();

$table->string('password');

$table->rememberToken();

$table->timestamps();

});

Schema::create('roles', function (Blueprint $table) {

$table->increments('id');

$table->string('name');

$table->timestamps();

});

Schema::create('role_user', function (Blueprint $table) {

$table->integer('user_id')->unsigned();

$table->integer('role_id')->unsigned();

$table->foreign('user_id')->references('id')->on('users')

->onDelete('cascade');

$table->foreign('role_id')->references('id')->on('roles')

->onDelete('cascade');

});

```

#### Create Models

**User Model**

```php

<?php

namespace App;

use Illuminate\Notifications\Notifiable;

use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable

{

use Notifiable;

/ **

* The attributes that are mass assignable.

*

* @var array

*/

protected $fillable = [

'name', 'email', 'password',

];

/ **

* The attributes that should be hidden for arrays.

*

* @var array

*/

protected $hidden = [

'password', 'remember_token',

];

/ **

* The roles that belong to the user.

*/

public function roles()

{

return $this->belongsToMany(Role::class, 'role_user');

}

}

```

**Role Model**

```php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Role extends Model

{

public function users()

{

return $this->belongsToMany(User::class, 'role_user');

}

}

```

**UserRole Model**

```php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class UserRole extends Model

{

}

```

Now we can create records

```php

$user = User::find(2);

$roleIds = [1, 2];

$user->roles()->attach($roleIds);

$user = User::find(3);

$roleIds = [1, 2];

$user->roles()->sync($roleIds);

$role = Role::find(1);

$userIds = [10, 11];

$role->users()->attach($userIds);

$role = Role::find(2);

$userIds = [10, 11];

$role->users()->sync($userIds);

```

Now we can retrieve records

```php

$user = User::find(1);

dd($user->roles);

$role = Role::find(1);

dd($role->users);

```

Hence laravel Eloquent is more powerful and we do relationships easily compared to native query. We will be having three more relationships in laravel. Ie.., has many, one to many polymorphic and many to many polymorphic. With eloquent relationship we can easily connect the tables each other. One to one relationships we can connect two tables with their basic functionalities. In one to many we will connect with single table with multiple options. In Many to many we will be having more tables.

SPONSORS