0
votes

i'm creating admin of my articles, in my resource EDIT post i have some problems, i would like show all tags of my post that i'm editing, i'm tryng like this:

I created a variable array with all tags id relation with the post edited:

 $post_tags[0]->tag_id // it return some id of tag's post

Now i would show all tag's post like input checked in my form edit.blade.php

    @for ($i = 0; $i < count($all_tags); $i++)

        @if($all_tags[$i]->id != $post_tags[$i]->tag_id)
           <input style="cursor: pointer;" type="checkbox" name="tags[]" id=" {{$all_tags[$i]->slug}}" value="{{$all_tags[$i]->id}}" data-parsley-mincheck="2"  class="flat"/>
        @else
           <input style="cursor: pointer;" type="checkbox" name="tags[]" id="{{$all_tags[$i]->slug}}" value="{{$all_tags[$i]->id}}" data-parsley-mincheck="2"  class="flat" checked/> 
    @endif

 @endfor

But i'm getting this error:

ErrorException in Collection.php line 1187: Undefined offset: 5 (View: C:\xampp\htdocs\sofis\resources\views\admin\post\edit.blade.php)

4

4 Answers

3
votes

Larvael 5.3 and above

As others have said, you need to check to make sure the index exists. You can also simplify your logic some by using @foreach instead of @for:

@foreach ($all_tags as $tag)
    <input style="cursor: pointer;" type="checkbox" name="tags[]" id=" {{$tag->slug}}" value="{{$tag->id}}" data-parsley-mincheck="2"  class="flat" {{ (isset($post_tags[$loop->index]) && $post_tags[$loop->index]->tag_id == $tag->id) ? 'checked' : '' }} />
@endforeach
1
votes

You could improve Samsquanch's answer to match with versions lesser than 5.3. You can access array index by defining $key in foreach() like shown bellow.

@foreach ($all_tags as $key => $tag)
    <input style="cursor: pointer;" type="checkbox" name="tags[]" id=" {{$tag->slug}}" value="{{$tag->id}}" data-parsley-mincheck="2"  class="flat" {{ (isset($post_tags[$key]) && $post_tags[$key]->tag_id == $tag->id) ? 'checked' : '' }} />
@endforeach
1
votes

This means $post_tags[$i] doesn't have element with index = 5. You shouldn't use $array[$index] method if you're not sure element with this index exists. Or you should check it before use:

@if (isset($post_tags[$i]) && $all_tags[$i]->id != $post_tags[$i]->tag_id)
0
votes

I guess $post_tags does not have index 5, so $post_tags[$i] fails