Laravel - Use PHP variabele in Javascript

Internal Javascript

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


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

View (index.blade.php):

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

External Javascript

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

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

Create the Script Controller:


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>