8

How can i pass an array in vue js via laravel(blade)? I tried to do so :

//$users - array blade:

<all-users users="{{ $users }}"></all-users>

vue:

<tr v-for="user in users" >

                    <td>{{ user.id }}</td>
                    <td>{{ user.login }}</td> 
</tr>

js:

export default {

    props:['users']
    }

//don't working all

P.S I tried also:
<all-users users="{{ $users[0]->toJson() }}"></all-users>
Output:

{"id":2,"email":"[email protected]","login":"SimpleUser","role_id":0,"images":"public\/img\/default_avatar.png","created_at":null,"updated_at":null}

In advance thanks for help

1
  • you say that your ouput return object but why do you loop your object in your vue?
    – Jay
    Commented Apr 10, 2018 at 8:32

4 Answers 4

16
<all-users :users='@json($users)'></all-users>

or

 <all-users :users='{{ json_encode($users) }}'></all-users>
4
  • 1
    I receive all data in json format. How can i sort it in vue js? Via "v-for" - don't work
    – Andrey
    Commented Apr 10, 2018 at 6:01
  • You can sort the json by @json($users->sortBy('name')) Commented Apr 28, 2018 at 12:04
  • 1
    the answer needs to updated with @hasan-wahajat, if using json use single quote, and add semicolon :
    – hendra1
    Commented Feb 6, 2020 at 17:41
  • So, I have a case where one value in my json contains ' (single quote) like daniel's and it still crashes the app. (I have tried escaping it at php level with every possible way but of no use) Commented Sep 8, 2023 at 12:09
8

To pass data from laravel to vue your best option is using the @json option provided by Laravel. So your code will be like so:

<all-users :users='@json($users)'></all-users>

Keep in mind that you need to use single quotations @json function. Also don't forget to use ":" for your user prop otherwise it will be interpreted as string.

Laravel docs for json data: https://laravel.com/docs/master/blade#displaying-data

1
<all-users :users='@json($usersInfo)'></all-users>

Also, keep in mind that you can't use a camel case here. It should be:

 <all-users :users='@json($usersinfo)'></all-users>
0
in Blade:

<div id="app">
  <all-users users="{{ $users }}"></all-users>
</div>

get in Vue:
 
export default({
  props:['users'],

  mounted: {
    console.log(this.users); // return your users
  }

});

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.