Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Wakanda's avatar
Level 10

Get unique belongstTomany by pivot column type giving priority to the latest date.

Hi Devs,

I have a model Animal that belongToManyResults

// Animal Table

   $table->string('name');
    $table->enum('gender', ['Male', 'Female']);
    $table->string('chip_number');
    $table->string('furstyle')->nullable();
     $table->string('pedigree_number');```


// Pivot table
$table->integer('type')->nullable();
 $table->date('issue')->nullable();
 $table->uuid('animal_id');
 $table->uuid('certificate_id');
 $table->foreign('animal_id')->references('id')->on('animals')->onDelete('cascade');
 $table->foreign('certificate_id')->references('id')->on('certificates')->onDelete('cascade');

//Certificate table
 $table->uuid('id')->primary();
  $table->string('name')->unique();
  $table->bolean('rival')->nullable();
``

Based on this structure using Laravel eloquent how can I get only a unique Animal certificate (unique by pivot column type) on the uniqueness give me the certificate with the latest date (condition pivot date)
0 likes
0 replies

Please or to participate in this conversation.