Search code examples
phpjquerytwitter-bootstraplaravelbootstrap-select

Can't send collection to bootstrap-select in Laravel form


Here is an edit form I've created

@extends('main')

@section('title', 'Edit Post')

@section('content')

    <form class="form-group" action="/categories/update" method="POST">
        {{csrf_field()}}
        <input name="_method" type="hidden" value="PUT">

        <label for="category_id" id="category_id">Select Category</label>
        <select class="form-control" id="category_id" style="height:auto;" name="category_id">
            @foreach($categories as $category)
                <hr class="custom-hr-heading"/>
                <option value="{{$category->id}}" {{($category->id == $post->category->id)?"selected='selected'":""}}>
                    {{$category->name}}
                </option>
            @endforeach
        </select>

        <label for="title" class="mt-2" name="title" id="title">Your Post Title</label>
        <input type="text" class="form-control mb-2" value="{{$post->title}}" name="title" id="title">

        <textarea class="form-control" name="body">{{$post->body}}</textarea>

        <label for="tags" id="tags" name="tags">Select Tags..</label>

        <select class="selectpicker mt-3" id="tags[]" name="tags[]" multiple="multiple">
            @foreach($tags as$tag)
                <option value="{{$tag->id}}">{{$tag->name}}</option>
            @endforeach
        </select>
        <br/>
        <button type="submit" class="btn mt-3 btn-success btn-sm">Update</button>

    </form>

    <script type="text/javascript">
        tinymce.init({
            selector: 'textarea',
            theme: 'modern',
            height: 300
        });

        $('.selectpicker').selectpicker({
            style: 'btn-info'
        });
    </script>
@stop



Controller
    public function edit($id)
        {
            $post = Post::find($id);
            $categories = Category::orderBy('name', 'asc')->get();
            $tags = Tag::orderBy('name', 'asc')->get();
            return view('posts.edit', compact('post', 'categories', 'tags'))
        }

I get a themed select box that just says nothing selected. Am I passing the tags collection to the select box correctly?

I'm using Laravel 5.5, PHP 7.2, and Bootstrap 4.

I've tried bootstrap-select via CDN and local files.


Solution

  • The problem was infact two problems. Bootstrap 4 (final) support is only available in the latest bootstrap-select beta release here

    Also my code was a little out. Here is the final working code.

    <select class="selectpicker mt-3 form-control" name="tags[]" multiple>
        @foreach($tags as $tag)
             <option value="{{$tag->id}}" {{$post->tags->contains($tag->id)?"selected='selected":""}}>{{$tag->name}}</option>
        @endforeach
     </select>