2

I have a table with a json column cast as array.

In my class:

protected $casts = [
    'row_ids' => 'array',
];

I access this column via a relationship in another class:

public function table_rows()
{
    return $this->hasMany(TableChannelRow::class, 'channel_api_id', 'api_id');
}

When I dd the relationship I can see the columns in the target table OK, with one of the columns containing an array as expected:

dd($channel->table_rows);

#attributes: array:4 [▼
  "api_id" => 2
  "table_api_id" => 1
  "channel_api_id" => 6
  "row_ids" => "[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42,  ▶"
]

In my Blade template page I check whether the current record id is in the column array like this:

@foreach($channels as $channel)

    @if(in_array($row->api_id, $channel->table_rows->row_ids)) true @endif

@endif

But this fails with:

Property [row_ids] does not exist on this collection instance.

What have I missed? Thanks.

0

1 Answer 1

5

Your table_rows relationship returns a collection. So you have to loop through the collection or grab the first instance in your collection:

$channel->table_rows->first()->row_ids
Sign up to request clarification or add additional context in comments.

4 Comments

Perfect! Thank you. I just did it by $channel->table_rows[0]->row_ids
@TheRealPapa No problem! Just curious, does your relation always return one row? If so, maybe you should change the relation to hasOne instead of hasMany.
Perfect x2! Xie xie! I will change the relation too. Thanks!
Hi @Chin Leung, I have another different Q related to this issue if you have a second ;-) ! stackoverflow.com/questions/55729084/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.