LARAVEL ELOQUENT RELATIONSHIP PART 1

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 makes it easy to connect with each table 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,

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

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

Model Query using Relationships

$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.


1.      ONE TO ONE RELATIONSHIPS

Here we are creating 2 tables
Users  and 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 a model for each table, 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
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',
    ];

    /**
     * Get the phone record associated with the user.
     */
    public function phone()
    {
        return $this->hasOne('App\Phone');
    }
}

Phone Model

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

$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

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

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


2.      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 a Post Model and Comment Model

 Post Model

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    /**
     * Get the comments for the blog post.
     */
    public function comments()
    {
        return $this->hasMany(Comment::class);
    }
}

Comment Model

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;

class Comment extends Model
{
    /**
     * Get the post that owns the comment.
     */
    public function post()
    {
        return $this->belongsTo(Post::class);
    }
}

Now we can create records

$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

$post = Post::find(1);
$comments = $post->comments;
dd($comments);

$comment = Comment::find(1);
$post = $comment->post;
dd($post);

3.      MANY TO MANY RELATIONSHIPS

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

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

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

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
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
namespace App;
use Illuminate\Database\Eloquent\Model;

class Role extends Model
{
    /**
     * The users that belong to the role.
     */
    public function users()
    {
        return $this->belongsToMany(User::class, 'role_user');
    }
}

UserRole Model

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;

class UserRole extends Model
{
}

Now we can create records

$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

$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 queries. We will be having three more relationships in laravel. Ie.., has many, one to many polymorphic and many to many polymorphic. With an eloquent relationship, we can easily connect the tables with each other. One to one relationships we can connect two tables with their basic functionalities. In one to many, we will connect with a single table with multiple options. Many to many, we will be having more tables.

Comments