laravelaccessoreloquent-relationshipmutators

Laravel - virtual column id -> uuid


I have two models:

Ingredient, Category

Each ingredient has a category id, each category has many ingredients.

The problem is that I use auto-increment ids for joins and queries internally, but only show UUIDs to end users.

So the Ingredient table looks like this:

id uuid name category_id

And the category table looks like this:

id uuid name

My data in ingredients looks like this:

id: 1,uuid:{a uuid}, name: Ingredient A, category_id: 1

When I do a Ingredient::get(), I want to return this:

uuid: {ingredient uuid}, name: Ingredient A, category_uuid: {the category uuid}

Based on what I am learning about Laravel, you can use accessors and mutators.

I set up

protected $appends = [
        'category_uuid'
    ];

and

public function category()
    {
        return $this->belongsTo(Category::class);
    }

    public function getCategoryUuidAttribute()
    {
        return $this->category()->uuid;
    }

But I get this error:

message: "Undefined property: Illuminate\Database\Eloquent\Relations\BelongsTo::$uuid"

What am I doing wrong?


Solution

  • It seems the issue was adding ->first() to the method chain, and that handled it.

    So it becomes:

    public function getCategoryUuidAttribute()
    {
        return $this->category()->first()->uuid;
    }