Why do some of my voucher relations return null? even though there is a voucher with that ID
And some relationships run well as in the picture below
This is code for dumping the results
dump(\App\Models\AffiliatorVoucher::find('27a4093d-2370-4c55-bc44-1f8ef8144067')->toArray());
dd(\App\Models\AffiliatorVoucherMember::with('voucher')->find(172)->toArray());
App\Models\AffiliatorVoucher
class AffiliatorVoucher extends Model
{
use HasFactory, SoftDeletes;
protected $guarded = [
'id',
];
protected $casts = [
'detail' => 'object',
];
public $incrementing = false;
public function members() :HasMany
{
return $this->hasMany(AffiliatorVoucherMember::class);
}
// ... other methods
}
App\Models\AffiliatorVoucherMember
class AffiliatorVoucherMember extends Model
{
use HasFactory;
protected $guarded = ['id'];
protected $casts = [
'detail' => 'object',
];
public function voucher() :BelongsTo
{
return $this->belongsTo(AffiliatorVoucher::class, 'affiliator_voucher_id');
}
}
Affiliator Vouchers Migration
public function up()
{
Schema::create('affiliator_vouchers', function (Blueprint $table) {
$table->uuid('id')->primary();
$table->foreignId('affiliator_id')->constrained()->onUpdate('cascade')->onDelete('cascade');
$table->foreignId('organization_id')->nullable()->constrained()->onUpdate('cascade')->onDelete('cascade');
$table->string('prefix')->nullable();
$table->string('code')->unique();
$table->tinyInteger('status')->default(1);
$table->bigInteger('discount_amount')->unsigned()->nullable();
$table->decimal('discount_percentage', 5, 2)->unsigned()->nullable();
$table->json('detail')->nullable();
$table->timestamps();
$table->softDeletes();
});
}
Affiliator Voucher Member Migration
public function up()
{
Schema::create('affiliator_voucher_members', function (Blueprint $table) {
$table->id();
$table->foreignUuid('affiliator_voucher_id')->constrained()->onUpdate('cascade')->onDelete('cascade');
$table->string('unique_id')->unique()->nullable();
$table->string('name')->nullable();
$table->string('email')->nullable();
$table->json('detail');
$table->timestamps();
});
}
For additional information, I'm using \Str::uuid()
for inserting the id, and I'm working on Laravel ^9.19.
Thank you in advance for the answers friends who helped answer this problem. ❤️
Refer to the documentation on handling models with UUIDs as primary keys:
https://laravel.com/docs/9.x/eloquent#uuid-and-ulid-keys
It surely will fix any issue you have.