laravel-5 passing variable to JavaScript

前端 未结 6 1091
慢半拍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 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:

    
    
    • 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:

    
    
    • 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.

    
    

    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

    
    
    • Serializing to JSON - Laravel docs

提交回复
热议问题