Imi
Imi

Reputation: 549

How to pass a variable from laravel 5.4 to vuejs

Is it possible to pass a variable from controller to vuejs? I have read some answers but nothing seems to work for me. I want to pass the variable $url to vue. I have tried some thing like this

var url = {!! $url !!}; this gives me syntax error: unexpected token in app.js

example url http://eventregistry.org/json/suggestConcepts?prefix=sam&lang=eng&callback=JSON_CALLBACK

Controller

class SearchCompanyName extends Controller
{
    public function getcompanyname($name)
    {
      return "http://eventregistry.org/json/suggestConcepts?prefix=" . $name . "&lang=eng&callback=JSON_CALLBACK";
    }   

    public function index()
    {  
       $url = $this->getcompanyname(Input::get("company_name_by_user"));
       return view('searchcompany', ['url' => $url]);

    }
}

vue app.js

Vue.component('search', require('./components/Searchnames.vue'));
const search = new Vue({
    el: '#search',
    data: {
    },
    method: {
        getMessages: function(){
            console.log('I am here')
        }()
    }
});

blade template

@section('content')
<div class="container">
{!! $url !!}
 <search></search>
</div>

@endsection

Upvotes: 0

Views: 1348

Answers (2)

Farhad Hossen
Farhad Hossen

Reputation: 273

You can use this package : https://github.com/laracasts/PHP-Vars-To-Js-Transformer

public function index()
{
    JavaScript::put([
        'foo' => 'bar',
        'user' => User::first(),
        'age' => 29
    ]);

    return View::make('hello');
}

Upvotes: 1

Chinonso Chukwuogor
Chinonso Chukwuogor

Reputation: 569

If you want to declare your javascript variable in a script tag within a blade file, you need to put the variable in quotes like so

<script>
  var url = '{{ $url }}';
</script>

Upvotes: 1

Related Questions