Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

SarahS's avatar
Level 12

Edit form with current checkbox values

I have a database with 3 tables: links, categories and category_link. Each Link can have many Categories, each Category can have many Links and the lookup is in the category_link table.

When I come to edit a Link I want to be able to see what Categories it already has and then edit them. But, I cannot seem to get the ticks to show in the boxes, this is my code for the checkboxes (I've removed the layouts and css for readability):

@foreach ($categories as $category)
		<input 
           		id="{{$category->id}}" 
               	value="{{$category->id}}" 
               	aria-describedby="category-description" 
                name="categories[]"
                type="checkbox" 
               	@if (in_array($category->id, $link->categories->id) ? 'checked' : '') @endif
		>
		<label for="{{$category->id}}">{{$category->category}}</label>
@endforeach

I currently get this error:

Exception
Property [id] does not exist on this collection instance. 

I'm not sure what it should be to get it to work. Thanks

0 likes
6 replies
SarahS's avatar
Level 12

@Nakov Thanks, it isn't crashing now but neither does it show any ticked boxes.

SarahS's avatar
Level 12

It looks like everything is working OK except that it is not echoing out 'checked'.

SarahS's avatar
Level 12

OK so I've got it to work by removing the @if. Not sure why that wouldn't work though.

This is what does work:

{{ $link->categories->contains($category->id) ? 'checked' : '' }}

Thanks for your help.

Nakov's avatar
Nakov
Best Answer
Level 73

@SarahS74 glad you figure it out. I didn't even noticed that you used the shorthand syntax.. ? : is the same as @if @else so that's why it didn't worked that way.

this will work as well:

@if ($link->categories->contains($category->id)) checked @endif
SarahS's avatar
Level 12

@Nakov Yeah, sometimes I get so caught up trying to solve problem I don't notice the obvious things! Thanks.

Please or to participate in this conversation.