Search code examples
javascriptphpjquerylaravelbootstrap-tags-input

Write a js expression inside laravel blade template


I am using tagsinput for some tagging operation. I want to add some default value to the tag field that is sent from controller. But it seems that the way i am trying to use the js expression is not working. Can anyone help me. Here is code.

<script>
    var cities = new Bloodhound({
                    datumTokenizer: Bloodhound.tokenizers.obj.whitespace('text'),
                    queryTokenizer: Bloodhound.tokenizers.whitespace,
                    local: members
                });
                cities.initialize();
    var elt = $('#researcher');
                elt.tagsinput({
                    itemValue: 'value',
                    itemText: 'text',
                    allowDuplicates: false,
                    typeaheadjs: {
                        name: 'cities',
                        displayKey: 'text',
                        source: cities.ttAdapter()
                    }
                });
    @foreach ($memberResearch->member as $member)
         {!! $text = $member->firstName." ".$member->lastName !!}
         {!! $id = $member->member_id !!}
         @if($member->pivot->role == "Researcher")
             elt.tagsinput('add' , {"value" : {{ $id }} , "text" :{{ $text }} });
         @endif
    @endforeach 
</script>

Solution

  • PHP and Javascript are two very seperate entities.

    For this kind of stuff, the best approach is for laravel to dump the contents (the data) into the page somewhere where the frontend (javascript) can then pick up.

    For example:

        // controller
        $appConfig = [ 'foo' => 'bar' ];
    
        // blade
        <script>
            var AppConfig = {!! ! empty($appConfig) ? json_encode($appConfig) : "{}" !!};
        </script>
    
        // js
        var foo = JSON.parse(AppConfig).foo;
        console.log(foo); // outputs bar