Daily archives: 19th January 2019


Using Laravel Polymorphic relationships for different user profiles

Laravel Eloquent polymorphic relations are similar to standard relationships, except that the model on one side of the relationship is defined by a column in the database table. Typically this would allow a single ‘child’ model to be attached to multiple different parents, for example, a Comment model can belong to a Post or a Page. An Image model can belong equally to an Item or a Category.  In this example we are going to reverse this typical arrangement and have the User model belong to different profile types.

Imagine a belongsTo relationship where in a table contains a foreign key to the ID of the other model, a polymorphic relationship uses an additional column to specify the model also.

In this example, we will be able to create tables (and models) that contain profile information for different types of users. The Admin user has one set of attributes and a Customer has a totally different set of attributes. Both types still use the User model for identification and access to our application.

Method

Assuming a simple Laravel installation, where php artisan make:authhas been used to create a basic authentication solution.

We can add an AdminProfile and CustomerProfile

php artisan make:model AdminProfile -m
php artisan make:model CustomerProfile -m

(the -m will create migrations as well as the model)

In the migration files, add the attributes that are specific to that type of user

Schema::create('admin_profiles',function(Blueprint$table){
  $table->increments('id');
  $table->string('department')->nullable();
  $table->string('payroll')->nullable();
  $table->string('manager')->nullable();
  $table->timestamps();
});

 Schema::create('customer_profiles', function (Blueprint $table) {
   $table->increments('id');
   $table->string('address1')->nullable();
   $table->string('address2')->nullable();
   $table->string('address_city')->nullable();
   $table->string('address_postcode')->nullable();
   $table->string('address_country')->nullable();
   $table->string('mobile')->nullable();
   $table->string('landline')->nullable();
   $table->timestamps();
 });

The only other database work to do is to add the polymorphic columns to the existing users table.  We can create a new migration to extend the users.

php artisan make:migration add_polymorphism_to_users --table=users
 Schema::table('users', function (Blueprint $table) {
   $table->string('profile_type')->nullable();
   $table->unsignedInteger('profile_id')->nullable();
 });

A little work on the models so that they have the polymorphic relationship

User Model

Add to the existing user model;

 protected $with = ['profile'];
 
 public function profile()
 {
   return $this->morphTo();
 }

AdminProfile Model

<?php namespace App; 

use Illuminate\Database\Eloquent\Model; 

class AdminProfile extends Model 
{ 
  protected $guarded = [];
  
  public function user() 
  { 
    return $this->morphOne('App\User', 'profile');
  }
}

CustomerProfile Model

<?php namespace App; 

use Illuminate\Database\Eloquent\Model; 

class CustomerProfile extends Model 
{ 
  protected $guarded = [];
  
  public function user() 
  { 
    return $this->morphOne('App\User', 'profile');
  }
}

Run the migrations php artisan migrate

We can now have two different profile types associated with any user.  Two users have been created, and they have no profile associated with them at the moment.

Let’s test it with Tinker;
$profile = App\AdminProfile::create(['manager'=>'Donald','department'=>'Retail'])
$profile->user()->save(User::find(1))

We now have created a profile for our administrator user and attached it to their user account

$profile = App\CustomerProfile::create(['address1'=>'Lilac Cottage','address2'=>'Leeming Lane'])
$profile->user()->save(User::find(2))

And created a customer profile and attached this user 2

We can check the database and see the profile_type column has been populated

Thanks to the $withattribute added to the user model, whenever we get a user, we will also get the profile fields

>>> User::find(1)
=> App\User {#2962
 id: 1,
 name: "john doe",
 email: "john@mycorp.com",
 email_verified_at: null,
 created_at: "2019-01-19 13:00:23",
 updated_at: "2019-01-19 13:06:06",
 profile_type: "App\AdminProfile",
 profile_id: 1,
 profile: App\AdminProfile {#2972
   id: 1,
   department: "Retail",
   payroll: null,
   manager: "Donald",
   created_at: "2019-01-19 13:05:39",
   updated_at: "2019-01-19 13:05:39",
   },
 }
>>> User::find(2)
=> App\User {#2966
 id: 2,
 name: "jane smith",
 email: "jane@hotmail.com",
 email_verified_at: null,
 created_at: "2019-01-19 13:00:54",
 updated_at: "2019-01-19 13:12:12",
 profile_type: "App\CustomerProfile",
 profile_id: 1,
 profile: App\CustomerProfile {#2980
   id: 1,
   address1: "Lilac Cottage",
   address2: "Leeming Lane",
   address_city: null,
   address_postcode: null,
   address_country: null,
   mobile: null,
   landline: null,
   created_at: "2019-01-19 13:12:02",
   updated_at: "2019-01-19 13:12:02",
   },
 }

Bonus

To make it easy to know what type of user profile we are dealing with, we can extend the User model with a couple of accessors

  public function getHasAdminProfileAttribute()
  {
    return $this->profile_type == 'App\AdminProfile';
  }

  public function getHasCustomerProfileAttribute()
  {
    return $this->profile_type == 'App\CustomerProfile';
  }


>>> User::find(2)->hasAdminProfile
=> false
>>> User::find(2)->hasCustomerProfile
=> true
>>>