3

I am trying that from controller pass values (from database column), to vue.js component (for select option in v-for), but when I send from controller to blade and get as prop in vue.js and put as data, I get every character in json as one select option.

How I can fix that to work properly and to put json object in v-for select?

RolesController.php

$roles = Roles::all('name');

        return view('users.create', ['users' => $users]);

And in the blade I pass value to vue component:

<users-add
roles="{{$roles}}"
></users-add>

My UsersAdd.vue:

<select>
  <option v-for="role in roles" :value="role">
     {{role}}
  </option>
</select>

But I get every character in the list from json in the select, instead to get every role name in every select row. For example I get:

{
"
n
a
m
e
"
:
"
m
o
d
e
r
a
t
o
r
"

Instead

moderator
2
  • 1
    Did you try passing an array? It seems to be parsing an object. Commented Nov 3, 2019 at 20:35
  • I was looking again at your code: it's parsing a string. What's the output of <body>{{ $roles }}</body>? Commented Nov 3, 2019 at 21:03

1 Answer 1

4

Assuming you have a function in your RoleController that looks similar to the following:

public function index()
{
    $roles = Role::all('name');

    $users = User:all(); // or however you're obtaining your users

    return view('users.create', compact('roles', 'users'));
}

In your users.create blade template, you want to have the following:

<users-add :roles="{{ $roles }}"></users-add>

Note the colon (:) before the roles prop.

Then in your UserAdd vue component, something like the following should work for you:

<template>
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <label for="role">Role</label>
                <select id="role" name="role">
                  <option v-for="role in this.roles" :value="role">
                     {{ role.name }}
                  </option>
                </select>
            </div>
        </div>
    </div>
</template>

<script>
    export default {
        props: [
            'roles'
        ]
    }
</script>
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much, it works ! I forgot colon (:) in the blade.
@bakero - Glad I could help. [:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.