Full Stack Vue.js & Laravel - How to use Vuejs Service Container Package

Full Stack Vue.js & Laravel - How to use Vuejs Service Container Package

In this full stack vue.js to Laravel tutorial explains how to use of the vuejs service container package. Laravel to Vue.js ~ Full Stack Vue.js & Laravel Integration (Vuejs Service Container Package)

In this full stack vuejs to laravel tutorial, we cover a wide array of topics ~ all of which circle around the use of the vuejs service container package (https://github.com/zhorton34/vue-service-container).

Order of topics we'll cover:
1: Installing the vue service container
2: Creating the vuejs service container
3: Injecting Php data into vue service container, utilizing laravel blade
4: Accessing the php content from within vuejs service container
5: Creating vuejs service providers (boot, register, afterLaunch, & when hooks - context object)
6. Creating a global Vue component within the welcome-page.js ServiceProvider
6: Laravel blade templates & vuejs templates within a single template
7. Configuring webpack aliases using webpack.mix.js
8: Implementing vuex store within service provider
9: Committing php data to vuex store BEFORE we mount our Vue instance to the DOM
10: Global Event Bus Service Provider
11: Filters vuejs Service Provider
12: Directives vuejs Service Provider
13: Implementing vue-router using a vuejs Service Provider
14: afterLaunch, hook into vue-router example
15: Code splitting (definition)
16: Code splitting (purpose)
17: Full Stack Laravel and vuejs code splitting implementation
18: Closing Thoughts

PHP variable to JavaScript In Laravel

PHP variable to JavaScript In Laravel

In PHP, there is always a limitation on pass PHP variable to the javascript file. Many PHP developers, face this issue. But Laravel has one package which is directly set the variable in js. So, you can use this package for passing a variable from controller to javascript.

In PHP, there is always a limitation on pass PHP variable to the javascript file. Many PHP developers, face this issue. But Laravel has one package which is directly set the variable in js. So, you can use this package for passing a variable from controller to javascript.

However, we know the Laravel framework is having the largest community. Similarly, Laravel having large package base. So, sometimes it is easy to use package rather use custom code. Moreover, you can use existing packages.

Pass PHP variable to JavaScript

Many times you often find the need to pass PHP variable or string to the javascript file. But for this, you can use the below package.

Install package

Just copy below package and paste into the composer.json file.

"laracasts/utilities": "^2.1"

Or similarly from command line or terminal run command:

composer require laracasts/utilities

Provider

Further, add the Service provider into the config/app.php file. Which is used for the binding. After this, you will get Javascript facade.

'providers' => [
    '...',
    'Laracasts\Utilities\JavaScript\JavaScriptServiceProvider'
];

Publish the Configuration:

Finally, publish the config using the below command.

php artisan vendor:publish --provider="Laracasts\Utilities\JavaScript\JavaScriptServiceProvider"

Further, it will copy the javascript.js file to the config folder. There are two variable you can assign the values. Firstly, you can set bind_js_vars_to_this_view. This will set the name of the view. Basically, this is a partial view. If more than one view then you can set in array. Secondly, js_namespace is where you can define the namespace of the js variable. By default, Laracasts is the variable but you can change it to something else.

Usage in controller

Import the Dependency

You can initialize the JavaScript variable in the controller. Initialize and import into the controller.

use Javascript;

Set Variable

Now, you can define the variable into the controller using Javascript. You can set the values in the key-value pair. Assign a value to the key.

$array = [
    'key' => value_here,
];
 
JavaScript::put($array);

So, put your value into the JavaScript variable using the value of an array. Once you define into the array and assign to the variable you can access it into the js file.

Now, your controller will look like below.

<?php
namespace App\Http\Controllers;
 
use Illuminate\Http\Request;
use JavaScript;
 
class VarController extends Controller
{
 
 
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        \JavaScript::put([
            'foo' => 'bar',
            'user' => 'user',
            'time' => '2019-04-29'
        ]);
        return view('pages/home');
    }
}

Access In JS file

Now, your blade file will look like below.

@extends('layouts.default')
@section('content')
    <div style="text-align:center">
        <h1>PHP var to JavaScript</h1>
         
    </div>
     
@stop
@section('scripts')
<script src='assets/app.js'></script>
@stop

In js file, you can access the set variable into the Laracasts namespace. Which you define in the javascript.js file.

console.log(Laracasts.foo); // access foo variable
console.log(Laracasts.user);// access user variable
console.log(Laracasts.time);// access time variable

In this way, you can directly access the set variable. This will give simple access for getting value into the js file. There is a limitation for getting the value into the js file. So this package will give you direct access into js file.

In many cases, this will give you the simplest solution. Many developers have to face this problem in developement. So, this post will give some relief from this problem. Let me know if you face any issue.

Thanks For Visiting, Keep Visiting. If you liked this post, share it with all of your programming buddies!

Laravael PHP, JavaScript help needed

First, I am developer for C, C++, C#, Android and Swift but I have absolutly no experience in JavaScript or PHP or Web development.

First, I am developer for C, C++, C#, Android and Swift but I have absolutly no experience in JavaScript or PHP or Web development.

I bought some source code for my backend server. It is kind of shop where I can enter products and store them. Now, I got everthying to work (even with 0 knowdlege in web development), but there is a text input field which checks for integer values. I want to insert decimal values like a price information, e.g. 19.99. It then complains that it has to be 19 or 20. I can not find the place where to change that or which class/function is responsible for checking that entered value. There is something called Blade. It is in HTML and javaScript as it seems to me. I can not find any class or a route to a file where the entered values go and get checked. I don't even know which class/file is responsible for writing the values to the database. I mean, wtf? It can not be that complicated to find out which file is responsible to handle the entered values. It drives me crazy. 

That is the input which only takes integer values.

This is the blade code:

{{-- resources/views/admin/dashboard.blade.php --}}
@extends('adminlte::page')

@section('title', 'Products')

@include('parts.header')

@section('content_header')
<div class="col-md-12">
<h2>Add new product</h2>
</div>

@stop

@section('content')
<div class="row">
<div class="col-sm-12">
<form method="post" action="{{ route('product.add') }}" enctype="multipart/form-data">
{{ csrf_field() }}

            @if(!$errors-&gt;isEmpty())
                &lt;div class="alert alert-danger alert-dismissible"&gt;
                &lt;button type="button" class="close" data-dismiss="alert" aria-hidden="true"&gt;×&lt;/button&gt;
                &lt;h4&gt;&lt;i class="icon fa fa-ban"&gt;&lt;/i&gt; Alert!&lt;/h4&gt;
                    @foreach ($errors-&gt;all() as $error)
                        &lt;div&gt;{{ $error }}&lt;/div&gt;
                    @endforeach
                 &lt;/div&gt;
            @endif

        &lt;div class="col-sm-12"&gt;
            &lt;div class="box box-primary"&gt;
                &lt;div class="box-header with-border"&gt;
                    &lt;h3 class="box-title"&gt;Details&lt;/h3&gt;
                &lt;/div&gt;
                &lt;!-- /.box-header --&gt;
                &lt;!-- form start --&gt;
                &lt;form role="form"&gt;
                    &lt;div class="box-body"&gt;
                        &lt;div class="row"&gt;
                            &lt;div class="col-sm-4 form-group "&gt;
                                &lt;label for="name"&gt;Name&lt;/label&gt;
                                &lt;input type="text" name="name" class="form-control" id="name" placeholder="Enter name" required&gt;
                            &lt;/div&gt;
                            &lt;div class="col-sm-4 form-group "&gt;
                                &lt;label for="name"&gt;Description&lt;/label&gt;
                                &lt;input type="text" name="description" class="form-control" id="name" placeholder="Enter description" required&gt;
                            &lt;/div&gt;
                            &lt;div class="col-sm-3 form-group "&gt;
                                &lt;label for="category"&gt;Select category&lt;/label&gt;
                                &lt;select name="category_id" class="form-control" required&gt;
                                    &lt;option value="" disabled selected&gt;Select your option&lt;/option&gt;
                                    @foreach($categories as $category)
                                        &lt;option value="{{ $category-&gt;id }}"&gt;{{ $category-&gt;name }}&lt;/option&gt;
                                    @endforeach
                                &lt;/select&gt;
                            &lt;/div&gt;
                        &lt;/div&gt;
                        &lt;div class="row"&gt;
                            &lt;div class="col-sm-4 form-group"&gt;
                                &lt;label for="price"&gt;Price&lt;/label&gt;
                                &lt;input type="number" name="price" class="form-control" id="price" placeholder="Enter price" required&gt;
                            &lt;/div&gt;
                            &lt;div class="col-sm-4 form-group"&gt;
                                &lt;label for="amount"&gt;Amount&lt;/label&gt;
                                &lt;input type="number" name="amount" class="form-control" id="amount" placeholder="Enter amount" required&gt;
                            &lt;/div&gt;
                            &lt;div class="col-sm-3 form-group"&gt;
                                &lt;div class="row"&gt;
                                    &lt;div class="col-sm-6"&gt;
                                        &lt;img id="myImg" alt="" style="width: 100%;"&gt;
                                    &lt;/div&gt;
                                    &lt;div class="col-sm-6"&gt;
                                        &lt;label for="image"&gt;Image&lt;/label&gt;
                                        &lt;input class="fullwidth input rqd" type="file" name="image" id="image" accept="image/*" onclick="fileClicked(event)" onchange="fileChanged(event)" required&gt;
                                        &lt;div id="log"&gt;&lt;/div&gt;
                                    &lt;/div&gt;
                                &lt;/div&gt;
                            &lt;/div&gt;

                        &lt;/div&gt;


                        &lt;div class="row"&gt;
                            &lt;div class="col-sm-6"&gt;
                                &lt;h4&gt;Variations&lt;/h4&gt;
                                &lt;div class="box-body table-responsive no-padding"&gt;
                                    &lt;table id="variationTable" class="table table-bordered table-hover dataTable" role="grid"&gt;
                                        &lt;thead&gt;
                                        &lt;tr role="row"&gt;
                                            &lt;th rowspan="1" colspan="1"&gt;#&lt;/th&gt;
                                            &lt;th rowspan="1" colspan="1"&gt;Owner&lt;/th&gt;
                                            &lt;th rowspan="1" colspan="1"&gt;Remove&lt;/th&gt;
                                        &lt;/tr&gt;
                                        &lt;/thead&gt;
                                        &lt;tbody&gt;

                                        &lt;tr role="row" class="odd"&gt;
                                            &lt;td&gt;1&lt;/td&gt;
                                            &lt;td&gt;
                                                &lt;input type="text" name="owner_id[]" placeholder="Enter owner" required&gt;
                                            &lt;/td&gt;
                                            &lt;td&gt;
                                                &lt;i class="fa fa-fw fa-remove"&gt;&lt;/i&gt;
                                            &lt;/td&gt;
                                        &lt;/tr&gt;
                                        &lt;/tbody&gt;
                                    &lt;/table&gt;
                                &lt;/div&gt;
                                &lt;button type="button" class="btn btn-default btn-sm addrow pull-right" style="height: 34px;"&gt;
                                    &lt;span class="glyphicon glyphicon-plus-sign"&gt;&lt;/span&gt; Add
                                &lt;/button&gt;
                                &lt;div class="clearfix"&gt;&lt;/div&gt;

                                &lt;div&gt;
                                    &lt;button type="submit" class="btn btn-primary"&gt;Submit&lt;/button&gt;
                                &lt;/div&gt;
                            &lt;/div&gt;
                            &lt;div class="col-sm-6"&gt;
                                &lt;h4&gt;Siblings&lt;/h4&gt;


                                &lt;div class="form-group"&gt;
                                    &lt;select name="siblings[]" class="form-control select2" multiple&gt;
                                        @foreach($products as $product)
                                            &lt;option value="{{ $product-&gt;id }}"&gt;{{ $product-&gt;name }} &lt;/option&gt;
                                        @endforeach
                                    &lt;/select&gt;
                                &lt;/div&gt;


                            &lt;/div&gt;
                        &lt;/div&gt;
                    &lt;/div&gt;
                    &lt;!-- /.box-body --&gt;
                &lt;/form&gt;
            &lt;/div&gt;
        &lt;/div&gt;
    &lt;/form&gt;
&lt;/div&gt;

</div>
@stop

@section('js')
@include('parts.footer');
@stop

Can somebody tell me where to find the code which handles the input? Where to find the function which checks for integer? I really searched every file, but somehow I am too stupid for that web stuff.

There is something like a class mentioned: col-sm-4 form-group but I can not find it?!?

Thanks.

Generate Laravel route URLs from JavaScript with Laroute

Generate Laravel route URLs from JavaScript with Laroute

Laroute is a Laravel package that allows us to port our routes over to JavaScript, and gives us a bunch of very familiar helper functions to use

Laroute

Laravel has some pretty sweet helper functions for generating urls/links and its auto-json-magic makes it building APIs super easy. It's my go-to choice for building single-page js apps, but routing can quickly become a bit of a pain.

Wouldn't it be amazing if we could access our Laravel routes from JavaScript?

This package allows us to port our routes over to JavaScript, and gives us a bunch of very familiar helper functions to use.

Installation

Install the usual composer way.

source-shell
composer require te7a-houdini/laroute

Configure (optional)

Copy the packages config files.

php artisan vendor:publish --provider='Te7aHoudini\Laroute\LarouteServiceProvider'

app/config/packages/Te7aHoudini/laroute/config.php

text-html-php

return [

    /*
     * The destination path for the javascript file.
     */
    'path' => 'public/js',

    /*
     * The destination filename for the javascript file.
     */
    'filename' => 'laroute',

    /*
     * The namespace for the helper functions. By default this will bind them to
     * `window.laroute`.
     */
    'namespace' => 'laroute',

    /*
     * Generate absolute URLs
     *
     * Set the Application URL in config/app.php
     */
    'absolute' => false,

    /*
     * The Filter Methode
     *
     * 'all' => All routes except "'laroute' => false"
     * 'only' => Only "'laroute' => true" routes
     * 'force' => All routes, ignored "laroute" route parameter
     */
    'filter' => 'all',

    /*
     * Action Namespace
     *
     * Set here your controller namespace (see RouteServiceProvider -> $namespace) for cleaner action calls
     * e.g. 'App\Http\Controllers'
     */
    'action_namespace' => '',

    /*
     * The path to the template `laroute.js` file. This is the file that contains
     * the ported helper Laravel url/route functions and the route data to go
     * with them.
     */
    'template' => 'vendor/te7a-houdini/laroute/src/templates/laroute.js',

    /*
     * Appends a prefix to URLs. By default the prefix is an empty string.
    *
    */
    'prefix' => '',

];

Generate the laroute.js

To access the routes, we need to "port" them over to a JavaScript file:

php artisan laroute:generate

With the default configuration, this will create a public/js/laroute.js file to include in your page, or build.

text-html-basic
<script src="/js/laroute.js"></script>

Note: You'll have to laroute:generate if you change your routes.

JavaScript Documentation

By default, all of the functions are under the laroute namespace. This documentation will stick with this convention.

action

Generate a URL for a given controller action.

source-js
/** 
 * laroute.action(action, [parameters = {}])
 *
 * action     : The action to route to.
 * parameters : Optional. key:value object literal of route parameters.
 */

laroute.action('[email protected]');

route

Generate a URL for a given named route.

source-js
/**
 * laroute.route(name, [parameters = {}])
 *
 * name       : The name of the route to route to.
 * parameters : Optional. key:value object literal of route parameters.
 */

 laroute.route('Hello.{planet}', { planet : 'world' });

url

Generate a fully qualified URL to the given path.

source-js
/**
 * laroute.url(name, [parameters = []])
 *
 * name       : The name of the route to route to.
 * parameters : Optional. value array of route parameters.
 */

 laroute.url('foo/bar', ['aaa', 'bbb']); // -> /foo/bar/aaa/bbb

link_to

Generate a html link to the given url.

source-js
/**
 * laroute.link_to(url, [title = url, attributes = {}]])
 *
 * url        : A relative url.
 * title      : Optional. The anchor text to display
 * attributes : Optional. key:value object literal of additional html attributes.
 */

 laroute.link_to('foo/bar', 'Foo Bar', { style : "color:#bada55;" });

link_to_route

Generate a html link to the given route.

source-js
/**
 * laroute.link_to_route(name, [title = url, parameters = {}], attributes = {}]]])
 *
 * name       : The name of the route to route to.
 * title      : Optional. The anchor text to display
 * parameters : Optional. key:value object literal of route parameters.
 * attributes : Optional. key:value object literal of additional html attributes.
 */

 laroute.link_to_route('home', 'Home');

link_to_action

Generate a html link to the given action.

source-js
/**
 * laroute.link_to_action(action, [title = url, parameters = {}], attributes = {}]]])
 *
 * action     : The action to route to.
 * title      : Optional. The anchor text to display
 * parameters : Optional. key:value object literal of route parameters.
 * attributes : Optional. key:value object literal of additional html attributes.
 */

 laroute.link_to_action('[email protected]', undefined, { planet : 'world' });
PHP Documentation

Ignore/Filter Routes

By default, all routes are available to laroute after a php artisan laroute:generate. However, it is sometimes desirable to have laroute ignore certain routes. You can do this by passing a laroute route option.

text-html-php
Route::get('/ignore-me', [
    'laroute' => false,
    'as'      => 'ignoreme',
    'uses'    => '[email protected]'
]);

Route::group(['laroute' => false], function () {
    Route::get('/groups-are-super-useful', '[email protected]');
});