laravel-5 passing variable to JavaScript

is there any ways that JavaScript can get the variable from compact controller Laravel-5.

Example: I have the code below:

   $langs = Language::all();
   return View::make('NAATIMockTest.Admin.Language.index',compact('langs'));

Can I get this langs and pass it to JavaScript? I already used PHP-Vars-To-Js-Transformer. But when I use JavaScript::put for two functions in the controller. It didn't work. Any help?

This is my code by using PHP-Vars-To-Js-Transformer:

LanguageController: This is my create and edit function :

public function create()
       {
          $names = $this->initLang();
          Javascript::put([
            'langs' => $names
            ]);

            return View::make('NAATIMockTest.Admin.Language.create',compact('names'));
    }
     public function edit($id)
     {
        //
          $lang = Language::findOrFail($id);
          $names = $this->initLang();
          Javascript::put([
            'langs' => $names
            ]);


           return View::make('NAATIMockTest.Admin.Language.edit', compact('lang'));
           // return View::make('NAATIMockTest.Admin.Language.edit');

    }

this is my View create:

 @extends('AdLayout')
     @section('content')
   <  script type="text/javascript">
      var app = angular.module('myApp', []);
      app.controller('langCtrl', function($scope) {
          $scope.languages = langs;
      });
   </script>

   <div class="container-fluid" ng-app="myApp" ng-controller="langCtrl">
      <div class="row">
        <div class="col-md-8 col-md-offset-2">
            <div class="panel panel-default">
                <div class="panel-heading">
                    <h2>Create language
                    </h2>
                </div>

                <div class="panel-body">
                    {!! Form::open() !!}
                        <p class="text-center">
                            {!! Form::label('Name','Language: ') !!}
                            <input type="text" name="searchLanguage" ng-model="searchLanguage">
                        </p>

                        <select name="Name[]" multiple size="10" ng-model="lang" ng-click="show()">
                            <option value="@{{v}}" ng-repeat="(k,v) in languages | filter:searchLanguage">
                                @{{v}}
                            </option>
                        </select><br>

                        <div class="text-center">
                            {!! Form::submit('Create',['class'=>'btn btn-primary']) !!}&nbsp;
                              {!!   Html::linkAction('NAATIMockTest\[email protected]', 'Back', null, array('class' => 'btn btn-primary')) !!}
                        </div>
                    {!! Form::close() !!}
                </div>
            </div>
        </div>
    </div>
    </div>
   @endsection

This is my View edit:

 @extends('AdLayout')
    @section('content')
    <script type="text/javascript">

    var app = angular.module('myApp', []);
    app.controller('langCtrl', function($scope) {
        $scope.languages = langs;
    });
   </script>

   <div class="container-fluid" ng-app="myApp" ng-controller="langCtrl">
       <div class="row">
          <div class="col-md-8 col-md-offset-2">
              <div class="panel panel-default">
                <div class="panel-heading"><h2>Edit #{{ $lang->id}}</h2></div>
                <div class="panel-body">
                    {!! Form::model($lang) !!}
                        {!! Form::label('Name','Language: ') !!}&nbsp;{{ $lang->Name }}
                        <!-- {!! Form::text('Name',null,['disabled']) !!}<br> -->
                        {!! Form::hidden('id') !!}<input type="text" name="searchLanguage" ng-model="searchLanguage">
                        </p>

                        <select name="Name[]" size="10">
                            <option value="@{{v}}" ng-repeat="(k,v) in languages | filter:searchLanguage">
                                @{{v}}
                            </option>
                        </select><br>
                        <div class="text-center">
                            {!! Form::submit('Update',['class'=>'btn btn-info']) !!}&nbsp;
                            {!! Html::linkAction('NAATIMockTest\[email protected]', 'Back', null, array('class' => 'btn btn-primary')) !!}
                        </div>
                    {!! Form::close() !!}
                </div>
            </div>
        </div>
    </div>
   </div>
   @endsection

my javascript.php in config folder:

<?php

    return [

    /*
    |--------------------------------------------------------------------------
    | View to Bind JavaScript Vars To
    |--------------------------------------------------------------------------
    |
    | Set this value to the name of the view (or partial) that
    | you want to prepend all JavaScript variables to.
    |
    */
    'bind_js_vars_to_this_view' => 'footer',
    'bind_js_vars_to_this_view' => 'NAATIMockTest.Admin.Language.create',
    'bind_js_vars_to_this_view' => 'NAATIMockTest.Admin.Language.edit',

    /*
    |--------------------------------------------------------------------------
    | JavaScript Namespace
    |--------------------------------------------------------------------------
    |
    | By default, we'll add variables to the global window object. However,
    | it's recommended that you change this to some namespace - anything.
    | That way, you can access vars, like "SomeNamespace.someVariable."
    |
    */
    'js_namespace' => 'window',

];

The idea is: I have a table language in mysql. I want to show the dropdown list with multiple attributes to choose, and I also want to search with angularjs as well. That's why I want to pass the variable from the controller to JavaScript. Additionally, I have the function inside LanguageController called initLang to check if any language is exist inside the database, it isn't displayed inside the dropdown list in create the view.

Answers:

Answer

One working example for me.

Controller:

public function tableView()
{
    $sites = Site::all();
    return view('main.table', compact('sites'));
}

View:

<script>    
    var sites = {!! json_encode($sites->toArray()) !!};
</script>

To prevent malicious / unintended behaviour, you can use JSON_HEX_TAG as suggested by Jon in the comment that links to this SO answer

<script>    
    var sites = {!! json_encode($sites->toArray(), JSON_HEX_TAG) !!};
</script>
Answer

Standard PHP objects

The best way to provide PHP variables to JavaScript is json_encode. When using Blade you can do it like following:

<script>
    var bool = {!! json_encode($bool) !!};
    var int = {!! json_encode($int) !!};
    /* ... */
    var array = {!! json_encode($array_without_keys) !!};
    var object = {!! json_encode($array_with_keys) !!};
    var object = {!! json_encode($stdClass) !!};
</script>

There is also a Blade directive for decoding to JSON. I'm not sure since which version of Laravel but in 5.5 it is available. Use it like following:

<script>
    var array = @json($array);
</script>

Jsonable's

When using Laravel objects e.g. Collection or Model you should use the ->toJson() method. All those classes that implements the \Illuminate\Contracts\Support\Jsonable interface supports this method call. The call returns automatically JSON.

<script>
    var collection = {!! $collection->toJson() !!};
    var model = {!! $model->toJson() !!};
</script>

When using Model class you can define the $hidden property inside the class and those will be filtered in JSON. The $hidden property, as its name describs, hides sensitive content. So this mechanism is the best for me. Do it like following:

class User extends Model
{
    /* ... */

    protected $hidden = [
        'password', 'ip_address' /* , ... */
    ];

    /* ... */
}

And somewhere in your view

<script>
    var user = {!! $user->toJson() !!};
</script>
Answer
$langs = Language::all()->toArray();
return View::make('NAATIMockTest.Admin.Language.index', [
    'langs' => $langs
]);

then in view

<script type="text/javascript">
    var langs = {{json_encode($langs)}};
    console.log(langs);
</script>

Its not pretty tho

Answer

Try this - https://github.com/laracasts/PHP-Vars-To-Js-Transformer Is simple way to append PHP variables to Javascript.

Answer

I know that the next lines are not optimized, but it is a fast and readable way to get it working:

<script>
    var sampleTags = [];
    @foreach ($services as $service)
        sampleTags.push('{{ $service->name }}');
    @endforeach
</script>

Edit: Sorry, if the string has special characters (like ó), it is necessary to use {!! $service->name !!}.

Answer

Is very easy, I use this code:

Controller:

$langs = Language::all()->toArray();
return view('NAATIMockTest.Admin.Language.index', compact('langs'));

View:

<script type="text/javascript">
    var langs = <?php echo json_decode($langs); ?>;
    console.log(langs);
</script>

hope it has been helpful, regards!

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.