Vue.js + Laravel 5.4.26

Vue.js

Vue.js – The Progressive JavaScript Framework

Getting started with Vue.js in Laravel:

  • I have simply followed Laravel documentation for setting up Vue.js
    • Here is the link – https://laravel.com/docs/5.4/frontend#writing-javascript
  • When the build is ready, add app.js from the public folder to your blade.php page’s footer
  •  Issues:
    • If you are getting an error saying the components not found, it means your script is executing before the document is ready
    • Make sure you have added app.js script at the end of the page

Adding new component (similar to ‘example’ component given with Laravel):

  • Components:
    • Components are one of the most powerful features of Vue. They help you extend basic HTML elements to encapsulate reusable code. At a high level, components are custom elements that Vue’s compiler attaches behavior to. In some cases, they may also appear as a native HTML element extended with the special is attribute.
  • Create a new component in resources/components called Greeting.vue
  • Add your bootstrap element inside template element
  • Create an instance of ‘greeting’ component in app.js
    • Add the following to app.js
      Vue.component('greeting', require('./components/Greeting.vue'));
  • execute ‘npm run dev’ to rebuild app.js
  • Add <greeting></greeting> element to your blade.php page
  • You should be able to see the Greeting.vue template appear on the page
  • camelCase vs. kebab-case

    HTML attributes are case-insensitive, so when using non-string templates, camelCased prop names need to use their kebab-case (hyphen-delimited) equivalents:

    Vue.component(‘child’, {
    // camelCase in JavaScript
    props: [‘myMessage’],
    template: ‘<span>{{ myMessage }}</span>’
    })
    <!– kebab-case in HTML –>
    <child my-message=“hello!”></child>

    Again, if you’re using string templates, then this limitation does not apply.

Adding a Vue message to the page: (Declarative rendering)

  • add the following to the app.js page
    new Vue({
     el: '#example',
     data: {
     message: 'Hello Vue.js!'
     }
    });
  • add the example element to your blade.php page
    @{{message}}
    • You won’t need ‘@’ to show the message if you are not using Vue.js in Laravel
  • Ref: https://vuejs.org/v2/guide/#Declarative-Rendering

Gulp-Vueify:

Ref: https://www.npmjs.com/package/gulp-vueify

v-bind Shorthand

<!– full syntax –>
<a v-bind:href=“url”></a>
<!– shorthand –>
<a :href=“url”></a>

v-on Shorthand

<!– full syntax –>
<a v-on:click=“doSomething”></a>
<!– shorthand –>
<a @click=“doSomething”></a>

Vue HTTP Requests:

  • by defaults axios is installed with npm vue installation for Laravel
  • If axios is installed use the following code for get request
    axios.get(url).then(function(resp){ //response code;});
  • If axios not installed you should use
    this.$http.get(url);
    • vue-resource has to be installed for getting $http to work

CSRF token fix with axios:

<meta name="csrf-token" value="{{ csrf_token() }}"> 
axios.defaults.headers.common['X-CSRF-TOKEN'] = document.querySelector('meta[name="csrf-token"]').getAttribute('content');

Ref:

Laravel Retrieving data from database

Setup .env & config/database.php:

  1. Config/database.php file gets the database settings from .env file
    • eg:
      • ‘host’ => env(‘DB_HOST’, ‘localhost’)
  2. To set DB settings dynamically in .env file, use the code from the following link in your controller:

Setting controller method:

  1. Call database table or view from your controller method in the following way:
    • public function index(){
      
       $users = DB::table('users')->get();
      
       return view('users/index', ['users' => $users]);
      
       }

Setting routes in Routes/web.php:

  1. Route instance has options to call controller methods directly:
    • Route::get('index','UsersController@index');

 

Viewing the user info:

  1. In users/index.blade.php :
    •  @foreach ($users as $user)
      <p>This user id is - {{ $user->user_id}}</p>
      
       @endforeach

Laravel Views

Blade Templates:

https://laravel.com/docs/5.4/blade

Installing bootstrap:

  • Use composer require twbs/bootstrap
  • php artisan make:provider BootstrapServiceProvider  to create a service provider
  • Add the following publishing code to the boot method
    • public function boot()
      
       {
      
       $this->publishes([__DIR__.'/../../vendor/twbs/bootstrap/dist' => public_path('vendor/bootstrap')], 'public');
      
       }
  • register bootstrap service provider in config/app.php
    • App\Providers\BootstrapServiceProvider::class in the list of service providers
  • Run php artisan vendor:publish –tag=public –force to publish bootstrap to the public folder
  • To automate this add php artisan vendor:publish –tag=public –force to post-install-cmd and post-update-cmd section of composer.json
    • "scripts": {
      
       "post-install-cmd": [
      
       "Illuminate\\Foundation\\ComposerScripts::postInstall",
      
       "php artisan optimize"
      
       "php artisan vendor:publish --tag=public --force"
      
       ],
      
       "post-update-cmd": [
      
       "Illuminate\\Foundation\\ComposerScripts::postUpdate",
      
       "php artisan optimize"
      
       "php artisan vendor:publish --tag=public --force"
      
       ]
      
       },
  • HTML Helpers
    • Run composer require “laracollective/html”
    • Add Collective\Html\HtmlServiceProvider::class  to the list of providers in config/app.php
    • Add ‘Html’ => Collective\Html\HtmlFacade::class  in the list of aliases
    • Usage:
      • Creating bootstrap file link:
        • {{ Html::style(‘vendor/bootstrap/css/bootstrap.min.css’) }}

Laravel Middleware

https://laravel.com/docs/5.4/middleware

Middleware provides convenient mechanism for HTTP requests entering your application. For example, Laravel includes a middleware that verifies the user of your application is authenticated. If the user is not authenticated, the middleware will redirect the user to the login screen. However, if the user is authenticated, the middleware will allow the request to proceed further into the application.

Registering Middleware

Global middleware:

  • app/Http/Kernel.php
    • $routeMiddleware

 

Laravel Routes

  • Basic routing
    • Route::get($uri, $callback);
      • Route::get(‘myapp’, function(){ return “hello world”;});
        • navigating to ‘/public/myapp’ returns ‘hello world’
      • Route::get(‘welcome’, function(){ return view(‘welcome’);});
        • navigating to ‘/public/welcome’ displays welcome ‘view’.
  • Available route methods:
    • Route::get($uri, $callback);
    • Route::post($uri, $callback);
    • Route::put($uri, $callback);
    • Route::delete($uri, $callback);
    • Route::patch($uri, $callback);
    • Route::options($uri, $callback);
    • for a route that needs to respond to multiple http verbs:
      • Route::match([‘get’,’post’], ‘myapp’, function(){  return “get/post”;  });
  • CSRF protection
    • forms pointing to put, post, delete routes should include CSRF token are else the request will be rejected
    • Adding CSRF protection:
      • <form> {{csrf_filed()}} </form>
  • Route parameters
    • Route::get(‘app/{id}’, function($id){ return “parameter in the url is”. $id; });
    • may define as many parameters as required:
      • Route::get(‘app/posts/{post}/comment/{comment}’, function($postid, $commentid){ return “parameters in the url are”. $postid. $commentid; });
  • Optional parameters
    • you can have optional parameters in the route:
      • Route::get(‘user/{id?}’, function($id = null){ return null});
  • Regular expression constraints
    • may constrain the format of the router parameters with ‘where’ method for a route instance
      • Route::get(‘user/{name}’, function ($name){ return $name;’})->where(‘name’, ‘[A-Za-z]+’);
      • Route::get(‘user/{id}’, function ($id){ return $id;’})->where(‘id’, ‘[0-9]+’);
      • Route::get(‘user/{id}/{name}’, function ($id, $name){ return $id.$name;’})->where([‘name’=> ‘[A-Za-z]+’, ‘id’=>'[0-9]+]’);
  • Global constraints
  • Name Routes
  • Route grouping – very useful
    • Middleware
    • Namespaces
    • Sub-Domain routing
    • Route pre-fixes
      • Route::group(['prefix' => 'users/admin'], function () {
        
         Route::get('login', function () {
        
         return 'This is users admin login';
        
         });
        
         Route::get('index', function () {
        
         return 'This is users admin home';
        
         });
        
        });
  • Route model binding
    • Route::get('api/users/{user}', function (App\User $user) {
          return $user->email;
      });
  • Explicit binding
  • Form method spoofing
  • Accessing the current route

Laravel folder structure

  • Routes – /app/Http/routes.php
  • Controllers – /app/Http/Controllers
  • Models – /app/modelname.php
  • Views – /resources/views/
  • Database
    • Migrations – /database/migrations
    • Seeds – /database/seeds
    • sqlite database storage – /storage
  • APP URL & DB Configuration – /.env
  • Composer file -/composer.json
  • All downloads by composer – /vendor/
  • App Configuration, Providers & Aliases – /config/app.php

Laravel Tutorial 2

Database configuration:

  • Specify the database being used in config/database.php
  • If you’re using sqlite, create an “database.sqlite” file in either databses or storage. We do not need to edit the “.env” file
    • Setting the path for database.sqlite
      • folder names are referenced with “_path” Eg: storage folder as “storage_path()”, database folder as “database_path()”
      • If the file is in the storage folder then you can write “storage_path(‘database.sqlite’)”, else if it is in the database folder then you can write “database_path(‘database.sqlite’)”
  • If you’re using mysql change the authentication details and edit the “.env” file

Migrations:

First we will need to set up database schema.

  • Migrations are version control for databases
  • Usually you create tables using GUI but these migrations help you create tables in the app. It will help the team to work with tables without using GUI but with code
  • Creating a migration doesn’t create the table. It will need to be migrated to get the tables created
  • You want to make a migration: Check these commands
    • php artisan make:migration nameofmigration
    • php artisan migrate — This will create the tables  in the database
  • You can roll back using Down functions in the migration class

Reference:

Seeding:

  • Laravel includes a simple method of seeding your database with test data using seed classes. All seed classes are stored in database/seeds. Seed classes may have any name you wish, but probably should follow some sensible convention, such as UsersTableSeeder, etc.
  • Adding some data to the tables for viewing something on the browser
  • Use “php artisan make:seeder UsersTableSeeder”
  • Add insert statements in the run method
  • DB::table(‘words’)->insert([ ‘word’=>’Modest’, ‘meaning’=>’Refusing to take any credit’, ‘language’=>’English’ ]);

  • Running Seeders:
    • php artisan db:seed
    • php artisan db:seed –class=UsersTableSeeder (for sepcific seeders)

Model:

  • To work with our database we need models
  • php artisan make:model User
  • model gets created in /app folder – ‘user.php’

Controllers:

  • To start hitting the browsers we need to set up some Controllers and Routes to point to them.
  • php artisan make:controller UsersController
  • controller gets created in /app/Http/Controllers folder

Routes: 

https://laravel.com/docs/5.4/routing

  • Routes location:
    • Laravel 5.2.45
      • app/http/routes.php is the main routes file
    • Laravel 5.4.26
      • /routes/web.php is the main routes file
    • User php artisan –version” to know version of Laravel
  • You can return a view by writing
    • Route::get(‘/’, function () { return view(‘welcome’); });
  • You can return resources from controller
    • Route:resource(‘users’,’UsersController’);
  • command prompt – php artisan route:list to view all the routes
  • You can do nested resources (joining tables)
  • Calling a function in a controller:
    • Route::get(‘about’,’UsersController@index’);
    • you should have index function in the UsersController.php page
      • public function index(){ return ‘Welcome to My Dictionary’; }
      • this will return the welcome message string when you navigate to /app/about
    • Returning a view:
      • Do not worry about the extension of the view or path of the view while referencing a view
      • can name the view like ‘folder.view’
    • Routing a model
      • Route::model(‘words’,’Word’);
  • app/users – which got both GET & POST works everywhere except Firefox

Route Model binding:

  • https://laracasts.com/series/laravel-5-fundamentals/episodes/18
  • route() helper function with a named route
  • routes.php ‘explicit binding’ –
    • Route::bind(‘words’, function($value) {
      return App\Word::where(‘userid’,$value)->first();
      });
    • which lets you use App/users/1 and shows all the details on the page

Reference:

Views:

  • To have consistent layouts across follow –  https://laravel.com/docs/5.0/templates#blade-templating
  • Reading & showing data is done – you don’t need to write any database queries to get the data from the database – it is done by Laravel

Reference:

Create/Edit/Delete:

Create:

  • Creating a “Create User” link in the index.blade.php file
  • {{ HTML::linkRoute(‘create’, ‘Add Word’) }}
    • In Laravel 5.0 HTML & Form helpers not added by default anymore
    • add “laravelcollective/html” in the required array of the composer file
    • Add the following in config/app.php file
      • add providers – “Collective\Html\HtmlServiceProvider::class”
      • add alliases – ‘Form’ => Collective\Html\FormFacade::class‘Html’ => Collective\Html\HtmlFacade::class,
    • https://laravelcollective.com/docs/5.2/html

Create & Edit View:

  • create.blade.php & edit.blade.php needs to be created
  • <!-- /resources/views/projects/create.blade.php -->
    @extends('app')
     
    @section('content')
        <h2>Create Project</h2>
     
        {!! Form::model(new App\Project, ['route' => ['projects.store']]) !!}
            @include('projects/partials/_form', ['submit_text' => 'Create Project'])
        {!! Form::close() !!}
    @endsection
     
    <!-- /resources/views/projects/edit.blade.php -->
    @extends('app')
     
    @section('content')
        <h2>Edit Project</h2>
     
        {!! Form::model($project, ['method' => 'PATCH', 'route' => ['projects.update', $project->slug]]) !!}
            @include('projects/partials/_form', ['submit_text' => 'Edit Project'])
        {!! Form::close() !!}
    @endsection
  • Form View: /_form.blade.php
    • {!! Form::label(‘name’, ‘Name:’) !!} {!! Form::text(‘name’) !!}

      {!! Form::label(‘slug’, ‘Slug:’) !!} {!! Form::text(‘slug’) !!}

      {!! Form::label(‘completed’, ‘Completed:’) !!} {!! Form::checkbox(‘completed’) !!}

      {!! Form::label(‘description’, ‘Description:’) !!} {!! Form::textarea(‘description’) !!}

      {!! Form::submit($submit_text) !!}

  • Fixing mass assignment exception by addin – protected $guarded = []; to model “user.php” in app folder
  • You can start adding users
  • Note – If the primary key is not ‘id’ for a table it won’t update. You’ll have to change the the primary key in your model (Eloquent ORM (Object Reference Model)). Eg -> protected $primarykey=’userid’;
  • CRUD operations done
  • Flash Messages:
    • These are the messages that can be shown after a successful request

Things to do:

  • How to remove /public/app etc and make it /app without giving access to .env file?
  • How to add bootstrap & styling?
  • How to add JS if required?
  • How to move this localhost built app to a new server?

Whole Project Reference:

Github Repo:

Laravel Tutorial

Using Laravel:
1) Created database for Laravel, you can see the options in for various database servers on config.php
2) Use any database server and set the parameters on config/database.php and also on the ‘env’ file on the root directory
3) for installing migration “php artisan migrate:install”
4) migrate table gets created
5) to make a migration “php artisan make:migration create_authors_table”
6) on successful creation open migrations, open the created migration
7) create schema in ‘up’ function of the class, drop schema in ‘down’ function
8) Schema query builder is used for creating tables
9) run migrations by using “php artisan migrate”
10) fluent query builder is used for inserting & updating tables
11) DB:: for crud operation into table
12) php artisan migrate:rollback for executing ‘down’ in the migrations (1 step at a time)
13) php artisan migrate:reset for executing ‘down’ on all migrations at once