Richard-MX
Richard-MX

Reputation: 484

How to pass a Laravel filtered collection as array to Vue?

I have a component which I'm trying to make it receive an array.

If I do it like this in a blade file:

<mega-menu :grouped-categories="{{ $categories->toJson() }}"></mega-menu>

It works as intended. It appears in Vue as array.

However, if I try to run some collection methods like 'filter' and 'groupBy' and then apply 'toJson', Vue receives it as an Object which is not what I need.

<mega-menu
  :grouped-categories="{{ $categories->filter(function($category) { return $category['enabled']; })->groupBy('group)->toJson() }}">
</mega-menu>

I'm suspicious that something is happening during filtering or grouping that converts it into an array. Any ideas on how to manipulate ´$categories´ variable which is an instance of Collection and make it pass as array to Vue?

Upvotes: 1

Views: 3607

Answers (3)

saber tabatabaee yazdi
saber tabatabaee yazdi

Reputation: 4959

use

v-bind:color="{{json_encode($yourVariable)}}"

in element

for example:

<color-item v-bind:color="{{json_encode($yourVariable)}}" ></color-item>

in your controller:

$myArray = array("name" => "لوازمات");
$item =  "لوازمات";
$collection = Color::all();


return view('home', compact('item', 'collection', 'myArray', ...));

in your blade:

@extends('layouts.app', ['item' => $item,'myArray' => $myArray, 'colors'=> $collection])

pass variable into vuejs:

<primary-header 
   :colors="{{json_encode($colors)}}" 
   :item="{{json_encode($item)}}" 
   v-bind:my-array="{{json_encode($myArray)}}">

in your vuejs file

<template>
    <div>
        {{item}}
        {{colors[0].name}}
        {{myArray.name}}
  
    </div>
</template>

<script>

    export default {
        name: "primary-header",
        props: {
            item:  String,
            myArray: Object,
            colors: Array
        },
        methods: {
        }
    };
</script>

<style scoped>
</style>

Upvotes: 0

Mathias
Mathias

Reputation: 67

To avoid problems with special chars add addslashes in template like:

:users="'{{ addslashes(\App\Users::all()->toJson()) }}'"

In vue component get the Users as prop:

props: {
    users: String
},

And add it to data

data() {
    return {
        users: JSON.parse(this.mailinglists)
    };
},

Hope this helps.

Upvotes: 1

Richard-MX
Richard-MX

Reputation: 484

According to the information provided by @Vivick, the associative arrays pass to Javascript as Objects. So I'll handle the Object inside the Vue component.

Upvotes: 1

Related Questions