Ravi Wadhwani
Ravi Wadhwani

Reputation: 145

Laravel one to many (polymorphic) relationship

I am creating a Laravel project in which Admins & Executives can have Clients.

Admin model

public function clients()
{
    return $this->morphMany('App\Client', 'executable');
}

Client.php

public function executable()
{
    return $this->morphTo();
}

Clients table

public function up()
{
    Schema::create('clients', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name',100);
        $table->morphs('executable');
        $table->timestamps();
    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::dropIfExists('clients');
}

While doing dd()

$data = App\Admin::find(1)->clients()->get(); It returns null

Collection {#524 ▼
  #items: []
}

Upvotes: 2

Views: 3562

Answers (2)

Juan Carlos Ibarra
Juan Carlos Ibarra

Reputation: 1399

Once your database table and models are defined, you may access the relationships via your models. For example, to access all of the clients for a Admin, you can use the clients dynamic property:

$data = App\Admin::find(1)->clients;

Upvotes: 1

Kit Loong
Kit Loong

Reputation: 373

Would you please paste more information of your code?

Especially how you seed your admins and clients record.

Below works for me.

public function testRun()
{
    Artisan::call('migrate');

    $admin = new Admin();
    $admin->id = 1;
    $admin->save();

    $client = new Client();
    $client->id = 11;
    $client->name = 'name';
    $client->executable_id = 1;
    $client->executable_type = 'App\Admin';
    $client->save();

    dd(Admin::find(1)->clients()->get());
}

Result

Illuminate\Database\Eloquent\Collection {#899
  #items: array:1 [
    0 => App\Client {#900
      #connection: "sqlite"
      #table: "clients"
      #primaryKey: "id"
      #keyType: "int"
      +incrementing: true
      #with: []
      #withCount: []
      #perPage: 15
      +exists: true
      +wasRecentlyCreated: false
      #attributes: array:6 [
        "id" => "11"
        "name" => "name"
        "executable_type" => "App\Admin"
        "executable_id" => "1"
        "created_at" => "2019-02-16 16:48:59"
        "updated_at" => "2019-02-16 16:48:59"
      ]
      ...

Upvotes: 3

Related Questions