Transfer Data to Views and Vue.js in Laravel

Laravel 5.4

Laravel 5.4 uses Vue.js as its default front-end JavaScript library.

This raises a new aspect in data transfer between controllers and views. Here we detail how to do it with Vue.js components being used within Blade templates.

The Controller

The controller, TheatreController, transfers data to the view. One of the data elements is an array of strings.

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;

class TheatreController extends Controller
{
    public function act(Request $request, $name)
    {
        return view('theatre/act', [
            'name' => $name, 
            'situation' => 'calming', 
            'array' => array('one', 'two', 'three', 'four')
        ]);
    }

}

The View

A Laravel blade template, theatre/act.blade.php, which calls a Vue component dynamic passing the message and array parameters to the component.

@extends('layouts.app')

@section('content')

<div class="container">
    <h1>Hello, {{ $name }}</h1>
</div>

<div class="well">
    <dynamic my-message="{{ $situation }}" array="{{ json_encode($array) }}"></dynamic>
</div>

@endsection

Note that we JSON encode the array parameter.

The Vue.js Component

Define in resources/assets/js/components/dyanmic.vue:

<template>
    <div class="container">
        <div class="row">
            <div class="col-md-8 col-md-offset-2">
                <div class="panel panel-default">
                    <div class="panel-heading">Example Component</div>

                    <div class="panel-body">
                        Here is my message to you: {{ myMessage }}!
                    </div>
                </div>
            </div>
        </div>
        <div class="row">
            And the opposite of my message: {{ reverseMyMessage }}
        </div>
        <div class="well">
            <ul id="example-1">
              <li v-for="item in ar">
                {{ item }}
              </li>
            </ul>
        </div>
    </div>
</template>

<script>
    export default {
        props: ['myMessage', 'array'],

        data: function() {
          return {
            reverseMyMessage: this.myMessage.toUpperCase(),
            ar: JSON.parse(this.array)
          }
        }
    }
</script>

Note that we JSON parse the array prop.