Laravel

Laravel is free, open source and most popular framework of PHP. It is based on Symfony and follows model-view-controller (MVC) architecture.Taylor Otwell created Laravel in June 2011. Furthermore, Laravel provides powerful tools for large and robust applications.

Eloquent

Laravel has an object-relational mapper (ORM) named “Eloquent” which allows you to work with your database. Eloquent is a new technique to work with database query using the model in Laravel. Eloquent provide simple and beautiful syntax to gain complex queries in few seconds without writing long queries.

Thus, each database table has an identical “Model” which we can use to interact wvcith that table. Models allow you to insert a new record or execute a query for data from the database table.

Now,  let’s take an example User model which we will use to store and retrieve data from our ‘users’ database table.

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
    // 
}

Relationship

A relationship, in the context of the database, is relation or link between two tables via primary key and reference key. One table has a foreign key that references the primary key of another table. Relationships allow relational databases to split and store data in different tables.

Database tables are often related to one another. For example, a user may have many profiles, or an event could be related to the user who organized it. With the help of eloquent, we can easily manage and working with these relationships, and it supports several different types of relationships.

Defining Relationship

Eloquent relationships are defined as functions or methods on model classes. A relationship also serves as powerful query builders like Eloquent models. We can use powerful method chaining and query capabilities by defining a relationship as a method. For example, we may chain additional constraints on this events relationship.

$user->events()->where('status', 'ACTIVE')->get();

One To One Relationship

One To One Relationship is very primary and vital relationship. Here one table associated with a single table.

Let’s look at an example. Here we have 2 models (User and Listing) and 2 tables (users and listings) for example.

Rules:

  • The User can create one Profile.
  • The Profile can be created by one User.

To define this relationship, we place aprofile method on the User model. The profile method should call the hasOne method and return its result.

Eloquent Models

class User {
  public function profile() {
    return $this -> hasOne(Profile::class);
  }
}
class Profile {
  public function user() {
    return $this -> belongsTo(User::class);
  }
}

Database Migrations

Schema::create('users', function(Blueprint $table) {
   $table -> increments('id');
   $table -> string('name');
 });
 Schema::create('profiles', function(Blueprint $table) {
   $table -> increments('id');
   $table -> string('name');
   $table -> integer('user_id') -> unsigned() -> index() - > nullable();
   $table -> foreign('user_id') -> references('id') -> on('users');
 });

Store Records

// Create relation between user and Profile.
$user -> profile() -> save($profile);
// Create relation between Profile and User.
$profile -> user() -> associate($user) -> save();

Retrieve Records

// Get User Profile
User::find(1) -> profile;
// Get Profile User 
Profile::find(1) -> user;

One To Many Relationship

One to Many relationship is used when one table associated with multiple tables. For example, a user may have multiple profiles.

Same as other relationships, we can define one-to-many relationships by placing a method on an Eloquent model.

Rules

  • The User can have many Profiles.
  • The Profile can be created by on User.

To define this relationship, we place aprofile method on the User model. The profile method should call the hasMany method and return its result.

Note, Eloquent will automatically figure out foreign key column on the profile model. By it’s convention, Eloquent takes the “snake case” name of it’s own model and suffix it with _id.

Eloquent Models

class User {
  public function profiles() {
    return $this -> hasMany(Profile::class);
  }
}
class Profile {
  public function user() {
    return $this -> belongsTo(User::class);
  }
}

Database Migrations

Schema::create('users', function(Blueprint $table) {
  $table -> increments('id');
  $table -> string('name');
});
Schema::create('profiles', function(Blueprint $table) {
  $table -> increments('id');
  $table -> string('title');
  $table -> integer('user_id') -> unsigned() -> index() ->  nullable();
  $table -> foreign('user_id') -> references('id') -> on('users');
});

Store Records

// Create relation between User and Profile. 
$user -> profiles() -> saveMany([$profile1, $profile2, ]);
// Or use the save() function for single model.
$thief -> profiles() -> save($profile);
// Create relation between Profile and User.
$profile -> user() -> associate($user) -> save();

Retrieve Records

// Get User Profile 
$user -> profiles;
// Get Profile User
$profile -> user;

Polymorphic One To Many Relationship

Polymorphic one-to-many relationship used when a model belonging to more than one other model on a single association. For example, Male (Person) and Female (Person) can eat Apples but an apple could be eaten by one person (Male or Female).

Rules

  • The Male (person) can eat many Apples.
  • The Female (person) can eat many Apples.
  • The Apple can be eaten by one person (Male or Female).

To define this relationship, we place aapples method on the Male model as well as inFemale model. The apples method should call the morphMany method and return its result. InAppleclass we place person method which should call morphTo method.

Eloquent Models

class Male {
  public function apples() {
    return $this -> morphMany(Apple::class, 'person');
  }
}
class Female {
  public function apples() {
    return $this -> morphMany(Apple::class, 'person');
  }
}
class Apple {
  public function person() {
    return $this -> morphTo();
  }
}

Database Migrations

//Create 'male' table 
 Schema::create('male', function(Blueprint $table) {
   $table -> increments('id');
   $table -> string('name');
 });
 //Create 'female' table 
 Schema::create('female', function(Blueprint $table) {
   $table -> increments('id');
   $table -> string('name');
 });
 //Create 'apples' table 
 Schema::create('apples', function(Blueprint $table) {
   $table -> increments('id');
   $table -> string('color');
   $table -> integer('person_id') -> unsigned() -> index() -> nullable();
   $table -> string('person_type') -> nullable();
   // or use
   $table -> morphs(‘person’);
   instead of "person_id"
   and "person_type"
 });

Store Records

// Create relation between person (Male/Female) and Apple.
 $male -> apples() -> saveMany([$apple1, $apple2, ]);
 $female -> apples() -> saveMany([$apple1, $apple2, ]);
 // Or use the save() function for single model. 
 $male -> apples() -> save($apple);
 $female -> apples() -> save($apple);
 // Create relation between Apple and person (Male/Female). 
 $apple1 -> person() -> associate($male) -> save();
 $apple2 -> person() -> associate($female) -> save();

Retrieve Records

// Get person (Male/Female) Apples 
 $male -> apples $female -> apples
 // Get Apple person (Male and Female)
 $apple -> person

Many To Many Relationship

Many-to-many relationships are bit complicated than one-to-one and one-to-many relationships. An example of such a relationship is a user with many mobile phones, where the mobile phones are also shared by other users.

Rules

  • The User can use many Phones.
  • The phone can be used by many Users.

To defile many-to-many relationship three tables are required:users, phones andphone_user. Thephone_usercontains phone_id and user_id columns.

Eloquent Models

class User {
  public function phones() {
    return $this -> belongsToMany(Phone::class);
  }
}
class Phone {
  public function users() {
    return $this -> belongsToMany(User::class);
  }
}

Database Migrations

//Create 'users' table
Schema::create('users', function(Blueprint $table) {
  $table - > increments('id');
  $table - > string('name');
});
//Create 'phones' table
Schema::create('phones', function(Blueprint $table) {
  $table - > increments('id');
  $table - > string('name');
});
//Create 'phone_user' table 
Schema::create('phone_user', function(Blueprint $table) {
  $table - > increments('id');
  $table - > integer('phone_id') - > unsigned() - > index();
  $table - > foreign('phone_id') - > references('id') - > on('phones') - > onDelete('cascade');
  $table - > integer('user_id') - > unsigned() - > index();
  $table - > foreign('user_id') - > references('id') - > on('users') - > onDelete('cascade');
});

Store Records

// Create relation between User and Phone.
$user - > phones() - > attach([$phone1 - > id, $phone - > id, ]);
// Or use the sync() function to prevent duplicated relations.
$user - > phones() - > sync([$phone1 - > id, $phone2 - > id, ]);
// Create relation between Phone and User. 
$phone - > users() - > attach([$user1 - > id, $user2 - > id, ]);
// Or use the sync() function to prevent duplicated relations.
$phone - > users() - > sync([$user1 - > id, $user2 - > id, ]);

Retrieve Records

// Get User Phone 
$user - > phones
// Get Phone Users
$phone - > users

Polymorphic Many To Many Relationship

With traditional polymorphic relations, Laravel provides many-to-many polymorphic to use. a polymorphic-many-to-many relationship is a bit complicated than the traditional polymorphic relationship.

Rules

  • The Male (person) can use many Phones.
  • The Female (person) can drive many Phones.
  • The Phone can be used by many persons (Male or/and Female).

The Pivot table “persons” should store the Person IDPerson Type and the Phone ID.

Eloquent Models

class Male {
  public function phones() {
    return $this - > morphToMany(Phone::class, 'person');
  }
}
class Female {
  public function phones() {
    return $this - > morphToMany(Phone::class, 'person');
  }
}
class Phone {
  public function males() {
    return $this - > morphedByMany(Male::class, 'person');
  }
  public function females() {
    return $this - > morphedByMany(Female::class, 'person');
  }
}

Database Migrations

Schema::create('males', function(Blueprint $table) {
  $table -> increments('id');
  $table -> string('name');
});
Schema::create('females', function(Blueprint $table) {
  $table -> increments('id');
  $table -> string('name');
});
Schema::create('persons', function(Blueprint $table) {
  $table -> increments('id');
  $table -> integer('person_id') -> unsigned() -> index();
  $table -> string('person_type');
  // or use
  $table -> morphs(‘person’);
  instead of "person_id"
  and "person_type"
  $table -> integer('phone_id') -> unsigned() -> index();
  $table -> foreign('phone_id') -> references('id') -> on('phones') -> onDelete('cascade');
});

Store Records

// Create relation between person (Male/Female) and Phone. 
$male -> phones() -> saveMany([$phone1, $phone2]);
$female -> phones() -> saveMany([$phone1, $phone2]);
// Or use the save() function for single model. 
$male -> phones() -> save($phone1);
$female -> phones() -> save($phone1);
// Create relation between Phone and person (Male/Female). 
$phone -> males() -> attach([$male1 -> id, $male2 -> id, ]);
$car -> females() -> attach([$female1 -> id, $female2 -> id, ]);
// Or use the sync() function to prevent duplicated relations. 
$phone -> males() -> sync([$male1 -> id, $male2 -> id, ]);
$phone -> females() -> sync([$female1 -> id, $female2 -> id, ]);

Retrieve Records

// Get person (Male/Female) Phones 
$male -> phones $female -> phones
// Get Phone persons (Male and Female)
$phone -> females $phone -> males