Skip to content
Advertisement

fill already available values into CRUD edit form in Laravel

Let’s say, I have a Laravel application with articles which can have several tags associated (i.e. an n:m relation). Creating those records is working pretty fine and I can also retrieve the selected tags array. All the necessary relations are available and working in Eloquent or in the models.

Now, I would like to create an edit form in this application. This edit form should show all the article details of one selected article in a pre-filled form where the user can change details. This is also working pretty fine for all the standard text fields. But I’m currently stuck in how to pre-select the currently assigned tags in the listbox of all available tags in this view, so that the user can both see what’s currently stored in the database and modify the assigned tags.

For example, I have an article which has assigned the tasks ‘fantasy’, ‘report’ and ‘news’. There are some more categories available, which could be selected, but currently aren’t, like ‘fun’ and ‘music’.

In that edit form, all the categories should be listed in the multi select field (i. e. fantasy, report, fun, news music), and the three assigned categories should be already selected (fantasy, report, news) for the currently selected article to be edited.

I know I can pass values from my Controller class to the view. But I’m not sure how to get that job done. I both need to pass the full list of all available tags and the list of the assigned tags. But if I did that, how would the matching of both arrays in the view be done, so that the correct entries are selected, but all entries of the tags table are shown?

Please excuse me for not providing screenshots, but I don’t have the full code, yet. It’s more that I would like to understand the basic steps here. If there are any tutorials or examples out there, it also would be great if you could point me to them.

(What I also should mention maybe: I am not using any of the {!! Form: items but I thought I would like to iterate through all the elements like below:

<select multiple class='' name='tags[]' id='tags>
@foreach ($tags as $tag)
    <option value="{{ $tag->id }}"  (selected?) >{{ $tag->name }}</option>
@endforeach
</select>

Any ideas?

Advertisement

Answer

If you work with Collection you can use “contains” and ” doesntContain”

and do something like this

@foreach($tags in $tag) 
   @if($assignedTags->contains($tag) 
      <option value="{{ $tag->id }}" selected >{{ $tag->name }}</option>
   @else
      <option value="{{ $tag->id }}">{{ $tag->name }}</option>
   @endif
@endforeach

probably not the best way to do it since that add ” logic ” in your view, try to create an Service and use blade dependency injection

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement