CrazyVito11
2 months ago
412
13
Laravel

Get belongsTo item value only, not as object

Posted 2 months ago by CrazyVito11

So I have a model that remembers a filename and tags of a image, so you can search through a lot of images easier. Now I have 2 other models (ImageTags and Tags). The reason why I have ImageTags and Tags is so I can reuse tags and autofill them when you upload a new image.

So tags only stores a unique ID and a string that holds the tag. While ImageTags holds a unique ID, the id of the image and the id of the tag that we linked to that image.

I got this to work, but the tag is returned as a object that then has a string inside it with the tag.

My Image model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Image extends Model
{
    protected $table = 'image';

    public function tagsList()
    {
        return $this->hasMany('App\ImageTags');
    }
}

My ImageTags model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class ImageTags extends Model
{
    protected $table = 'image_tags';

    public function tag()
    {
        return $this->belongsTo(Tags::class, 'tag_id', 'tag_id')->select('tag');
    }
}

My Tags model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Tags extends Model
{
    protected $table = 'tags';
}

this is what I get when I call $imageObject->tagsList :

[
  {
    "image_tag_id": 1,
    "image_id": 3,
    "tag_id": 1,
    "created_at": null,
    "updated_at": null,
    "tag": {
      "tag": "example tag 1"
    }
  },
  {
    "image_tag_id": 2,
    "image_id": 3,
    "tag_id": 2,
    "created_at": null,
    "updated_at": null,
    "tag": {
      "tag": "example tag 2"
    }
  }
]

What I want:

[
  {
    "image_tag_id": 1,
    "image_id": 3,
    "tag_id": 1,
    "created_at": null,
    "updated_at": null,
    "tag": "example tag 1"
  },
  {
    "image_tag_id": 2,
    "image_id": 3,
    "tag_id": 2,
    "created_at": null,
    "updated_at": null,
    "tag": "example tag 2"
  }
]

So if I would want to show all the tags in my blade I would have to write something like this:

@foreach($imageObject->tagsList as $tag)
            <div class="col-auto px-2">
                <div class="bg-info text-white p-2">
                    {{ $tag->tag->tag }}
                </div>
            </div>
        @endforeach

I would like to display it like this: {{ $tag->tag }} and not like {{ $tag->tag->tag }}

How can I make this work? I tried to add a pluck in ImageTags but that didn't work.

Thanks!

Please sign in or create an account to participate in this conversation.