Anastasie Laurent
Anastasie Laurent

Reputation: 915

using laravel option from javascript

in controller I do this

$actions = array('' => 'Select Action Name') + Action::lists('name' , 'id');

I want to use that $actions variable in my javascript.

I tried these ways:

<script>
var actions = {{actions}};
</script>

but I got this excpetion

Array to string conversion

I also tried this:

<script>
    @foreach($actions as $action)
        console.log($action);
    @endforeach
</script>

but in the console I got this exception

Uncaught ReferenceError: $action is not defined 

could you help me please?

Upvotes: 2

Views: 124

Answers (2)

Jeff Lambert
Jeff Lambert

Reputation: 24661

$actions is an array inside of your controller. To pass it down to a view, you could do this inside of a route callback of a controller:

return View::make('someview')->with('actions', $actions);

Then you would be able to access the $actions variable, an array, from within your view.

However, there are some big differences between Javascript Arrays and PHP arrays. Most likely, when you convert a PHP array to JavaScript you wind up with a JavaScript object instead, since arrays in javascript cannot have non-numeric indices.

What you probably want to do is json_encode your array in PHP, and then you can JSON.parse inside your JavaScript:

<script>
    var actions = {{ json_encode($actions) }};
    console.log(actions);
</script>

Upvotes: 1

Joseph Silber
Joseph Silber

Reputation: 219938

You have to echo it with curly braces:

<script>
    @foreach($actions as $id => $name)
        console.log('{{ $id }}', '{{{ $name }}}');
    @endforeach
</script>

Your other option is to use the array by converting it to JSON:

<script>
    var actions = {{ json_encode($actions) }};
</script>

Upvotes: 3

Related Questions