0
votes

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?

2
$this->category() is the BelongsTo class. $this->category is the Category class. - IGP

2 Answers

0
votes

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;
}
0
votes

You can also achieve this using Query Builder:

public function index()
{
    $ingredients = DB::table('ingredients')
        ->join('categories', 'ingredients.category_id', 'categories.id')
        ->select('ingredients.*', 'categories.uuid as c_uuid')
        ->get();

    return view('index', compact('ingredients'));
}
@foreach($ingredients as $ingredient)
   <ul>
        <li>{{ $ingredient->uuid }}</li>
        <li>{{ $ingredient->name }}</li>
        <li>{{ $ingredient->c_uuid }}</li>
   </ul>
@endforeach