laravel-5 passing variable to JavaScript

前端 未结 6 1075
慢半拍i
慢半拍i 2020-11-30 00:26

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

Example: I have the code below:

   $langs = Language::all()         


        
相关标签:
6条回答
  • 2020-11-30 00:59

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

    0 讨论(0)
  • 2020-11-30 01:03

    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>
    
    0 讨论(0)
  • 2020-11-30 01:07

    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>
    
    • Displaying unescaped data - Laravel docs
    • json_encode - PHP docs

    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>
    
    • Blade Templates - Laravel 5.5 docs

    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>
    
    • Serializing to JSON - Laravel docs
    0 讨论(0)
  • 2020-11-30 01:10
    $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

    0 讨论(0)
  • 2020-11-30 01:15

    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!

    0 讨论(0)
  • 2020-11-30 01:18

    Let's say you have a collection named $services that you are passing to the view.

    If you need a JS array with the names, you can iterate over this as follows:

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

    Note: If the string has special characters (like ó or HTML code), you can use {!! $service->name !!}.

    If you need an array of objects (with all of the attributes), you can use:

    <script>
      const myServices = @json($services);
      // ...
    </script>
    

    Note: This blade directive @json is not available for old Laravel versions. You can achieve the same result using json_encode as described in other answers.


    Sometimes you don't need to pass a complete collection to the view, and just an array with 1 attribute. If that's your case, you better use $services = Service::pluck('name'); in your Controller.

    0 讨论(0)
提交回复
热议问题