38

In my code I am using typeahead.js. I use Laravel 5 and I need to replace the var states with my {{ $jobs }} variable. I need to list all Job Titles as an array.

In my controller I have

$jobs = Job::all(['job_title']);

I know the loop method in javascript but I dont know how to "link" my blade's variable in the javascript. Anyone knows how to?

I have tried, in my.js

var jobs = {{ $jobs }}

But that wont work.

2
  • My question was asked first (7yrs + 1 month ago). The other was was only 7 years ago. How comes mine was closed? Commented May 17, 2022 at 19:00
  • 3
    The duplicate has more votes (both for the question and the answers). Age is not the only factor for the direction of a close vote. Commented May 20, 2022 at 10:52

11 Answers 11

44

For more complex variable types like arrays your best bet is to convert it into JSON, echo that in your template and decode it in JavaScript. Like this:

var jobs = JSON.parse("{{ json_encode($jobs) }}");

Note that PHP has to run over this code to make it work. In this case you'd have to put it inside your Blade template. If you have your JavaScript code in one or more separate files (which is good!) you can just add an inline script tag to your template where you pass your variables. (Just make sure that it runs before the rest of your JavaScript code. Usually document.ready is the answer to that)

<script>
    var jobs = JSON.parse("{{ json_encode($jobs) }}");
</script>

If you don't like the idea of doing it like this I suggest you fetch the data in a separate ajax request.

Sign up to request clarification or add additional context in comments.

12 Comments

Thanks for that but I got this in the console: SyntaxError: JSON.parse: expected property name or '}' at line 1 column 2 of the JSON data
Can you take a look at the source code of the page and see what's actually passed to JSON.parse?
It points to var jobs = JSON.parse("{{ json_encode($jobs) }}")
But this is inside a blade template isn't it?
@lukasgeiter can you not simply var jobs = {!! json_encode($jobs); !!}; ?
|
34

This works for me

jobs = {!! json_encode($jobs) !!};

Notice

Only use this method if you can guarantee that $jobs contains no user input values. Using {!! ... !!} outputs values without escaping them which could lead to cross-site scripting (XSS) attacks.

3 Comments

Assuming that $jobs is not client controlled and is safe from all kind of injections.
This works, but it concerns me, since I DO have user input values in my $jobs value. Can you edit the answer to include what to do if you have user input?
did the job for me. Thanks for this. Noted on the XSS attacks notice.
18

in laravel 6 this works for me

using laravel blade directive

var jobs = {!! json_encode($jobs) !!};

also used @json directive

var jobs = @json($jobs);

using php style

 var jobs = <?php echo json_encode($jobs); ?>

2 Comments

This solution worked for Laravel 8 as well
hi @jignesh can u help me stackoverflow.com/q/75150981/14913109
5

Just to add to above :

var jobs = JSON.parse("{{ json_encode($jobs) }}");

will return escaped html entities ,hence you will not be able to loop over the json object in javascript , to solve this please use below :

var jobs = JSON.parse("{!! json_encode($jobs) !!}");

or

var jobs = JSON.parse(<?php echo json_encode($jobs); ?>);

Comments

4

In laravel 7 I just do

var jobs = '{{ $jobs }}';

Comments

4

A simple way is by using the new @json() directive of Blade.

✓ Tested on Laravel 7.x

<script>
    let myVariable = @json($myVariable)
    console.log(myVariable)
</script>

Comments

2

this approach work for me:

var job = {!! json_encode($jobs ) !!}

and use in java script

Comments

1

In the newer laravel versions, in json "(double quotes) gets encoded into htmlentity as &quote; and unwanted JSON.parse() call by using this,

var jobs = JSON.parse("{{ json_encode($jobs) }}");

and you'll end up with the javascript error. Alternatively, you can use

var jobs = {!! json_encode($jobs, JSON_PRETTY_PRINT) !!};

As we know, {!! !!} is meant for printing HTML and it will work like a charm. This will reduce the overhead of parsing JSON at the browser as well.

Comments

0

I just solved this by placing a reference on the window Object in the <head> of my layout file, and then picking that reference up with a mixin that can be injected into any component.

TLDR SOLUTION

.env

GEODATA_URL="https://geo.some-domain.com"

config/geodata.php

<?php

return [
    'url' => env('GEODATA_URL')
];

resources/views/layouts/root.blade.php

<head>
    <script>
        window.geodataUrl = "{{ config('geodata.url') }}";
    </script>
</head>

resources/js/components/mixins/geodataUrl.js

const geodataUrl = {
    data() {
        return {
            geodataUrl: window.geodataUrl,
        };
    },
};

export default geodataUrl;

usage

<template>
    <div>
        <a :href="geodataUrl">YOLO</a>
    </div>
</template>

<script>
import geodataUrl from '../mixins/geodataUrl';

export default {
    name: 'v-foo',

    mixins: [geodataUrl],

    data() {
        return {};
    },

    computed: {},

    methods: {},
};
</script>

END TLDR SOLUTION

If you want, you can use a global mixin instead by adding this to your app.js entrypoint:

Vue.mixin({
    data() {
        return {
            geodataUrl: window.geodataUrl,
        };
    },
});

I would not recommend using this pattern, however, for any sensitive data because it is sitting on the window Object.

I like this solution because it doesn't use any extra libraries, and the chain of code is very clear. It passes the grep test, in that you can search your code for "window.geodataUrl" and see everything you need to understand how and why the code is working.

That consideration is important if the code may live for a long time and another developer may come across it.

However, JavaScript::put([]) is in my opinion, a decent utility that can be worth having, but in the past I have disliked how it can be extremely difficult to debug if a problem happens, because you cannot see where in the codebase the data comes from.

Imagine you have some Vue code that is consuming window.chartData that came from JavaScript::put([ 'chartData' => $user->chartStuff ]). Depending on the number of references to chartData in your code base, it could take you a very long time to discover which PHP file was responsible for making window.chartData work, especially if you didn't write that code and the next person has no idea JavaScript::put() is being used.

In that case, I recommend putting a comment in the code like:

/* data comes from poop.php via JavaScript::put */

Then the person can search the code for "JavaScript::put" and quickly find it. Keep in mind "the person" could be yourself in 6 months after you forget the implementation details.

It is always a good idea to use Vue component prop declarations like this:

props: {
    chartData: {
        type: Array,
        required: true,
    },
},

My point is, if you use JavaScript::put(), then Vue cannot detect as easily if the component fails to receive the data. Vue must assume the data is there on the window Object at the moment in time it refers to it. Your best bet may be to instead create a GET endpoint and make a fetch call in your created/mounted lifecycle method.

I think it is important to have an explicit contract between Laravel and Vue when it comes to getting/setting data.

In the interest of helping you as much as possible by giving you options, here is an example of making a fetch call using ES6 syntax sugar:

routes/web.php

Route::get('/charts/{user}/coolchart', 'UserController@getChart')->name('user.chart');

app/Http/Controllers/UserController.php

public function getChart(Request $request, User $user)
{
    // do stuff
    $data = $user->chart;

    return response()->json([
        'chartData' => $data,
    ]);
}

Anywhere in Vue, especially a created lifecycle method:

created() {
    this.handleGetChart();
},

methods: {
    async handleGetChart() {
        try {
            this.state = LOADING;
            const { data } = await axios.get(`/charts/${this.user.id}/coolchart`);

            if (typeof data !== 'object') {
                throw new Error(`Unexpected server response. Expected object, got: ${data}`);
            }

            this.chartData = data.chartData;
            this.state = DATA_LOADED;
        } catch (err) {
            this.state = DATA_FAILED;
            throw new Error(`Problem getting chart data: ${err}`);
        }
    },
},

That example assumes your Vue component is a Mealy finite state machine, whereby the component can only be in one state at any given time, but it can freely switch between states.

I'd recommend using such states as computed props:

computed: {
    isLoading() { return (this.state === LOADING); },
    isDataLoaded() { return (this.state === DATA_LOADED); },
    isDataFailed() { return (this.state === DATA_FAILED); },
},

With markup such as:

<div v-show="isLoading">Loading...</div>
<v-baller-chart v-if="isDataLoaded" :data="chartData"></v-baller-chart>
<button v-show="isDataFailed" type="button" @click="handleGetChart">TRY AGAIN</button>

Comments

0

In Laravel 8. You can use blade template por this...

const jobs = @json($jobs ?? NULL);

Comments

0
var job_id = '{{ $jobs->first()->id}}';

2 Comments

While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. You can find more information on how to write good answers in the help center: stackoverflow.com/help/how-to-answer . Good luck 🙂
This will cause problems if the value has single quotes in it

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.