Ga naar inhoud

Blog

Laravel - Use PHP variabele in Javascript

Internal Javascript

The quickest solution is to assign the variabele to a view and use internal javascript.

Controller:

return View::make('index', [ 'myVar' => $myVar ]);

View (index.blade.php):

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

External Javascript

Create a route to our fake .js file named script.js:

Route::get('/script.js', ['uses' => 'ScriptController@index']);

Create the Script Controller:

<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use View; use App\Http\Requests; use App\Http\Controllers\Controller; class ScriptController extends Controller { public function index() { return response()->view('script', [ 'myVar' => 'test' ])->header('Content-Type', 'application/javascript'); } }

Create the View (script.blade.php):

var myVar = '{{ $myVar }}';

In the template:

<script src="{{ URL::asset('script.js') }}"></script>