Friday 29 April 2016

Custom helpers in Laravel 5.1


Hi Everybody,

Today we will discuss about how to create custom helpers in laravel 5.1

Many times we create some function that further used in different controllers. To avoid multiple creation of same function in multiple controller, we can write these common function in helpers.

 

 Custom helpers’ directory


Our helpers will be located in the /app directory

Create a new directory Helpers in /app/Helpers

 

Helper class definition


Let’s now create a simple helper function that will concatenate two strings. Create a new file MyFuncs.php in /app/Helpers/MyFuncs.php Add the following code

<?php

namespace App\Helpers;

class MyFuncs {

    public static function full_name($first_name,$last_name) {
        return $first_name . ', '. $last_name;  
    }
}


HERE,

    1. namespace App\Helpers; defines the Helpers namespace under App namespace
    2. class MyFuncs {…} defines the helper class MyFuncs
    3. public static function full_name($first_name,$last_name) {…} defines a static function that accepts two string parameters and returns a concatenated string

 

Helpers service provide class


Service providers are used to auto load classes. We will need to define a service provider that will load all of our helper classes in /app/Helpers directory.

Run the following artisan command

php artisan make:provider HelperServiceProvider

The file will be created in /app/Providers/HelperServiceProvider.php

Open /app/Providers/HelperServiceProvider.php

Add the following code

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class HelperServiceProvider extends ServiceProvider {

   /**
    * Bootstrap the application services.
    *
    * @return void
    */
   public function boot()
   {
      //
   }

   /**
    * Register the application services.
    *
    * @return void
    */
   public function register()
   {
        foreach (glob(app_path().'/Helpers/*.php') as $filename){
            require_once($filename);
        }
   }
}
HERE,

    1. namespace App\Providers; defines the namespace provider
    2. use Illuminate\Support\ServiceProvider; imports the ServiceProvider class namespace
    3. class HelperServiceProvider extends ServiceProvider {…} defines a class HelperServiceProvider that extends the ServiceProvider class
    4. public function boot(){…} bootstraps the application service
    5. public function register(){…} is the function that loads the helpers
    6. foreach (glob(app_path().'/Helpers/*.php') as $filename){…} loops through all the files in /app/Helpers directory and loads them.

 

Helper Service Provider and class alias configuration


We now need to register the HelperServiceProvider and create an alias for our helpers.

Open /config/app.php file

Locate the providers array variable

Add the following line

App\Providers\HelperServiceProvider::class,

Locate the aliases array variable

Add the following line

'MyFuncs' => App\Helpers\MyFuncs::class,

Save the changes
Using our custom helper

Add the following route definition

<?php

namespace App\Http\Controllers;

use App\Helpers\MyFuncs;

class CustomerController extends Controller
{

    public function getCustomerName($id)
    {
        $response = $this->getCustomerDetail($id);
        $msg = "Customer detail.";
        return MyFuncs::
full_name($response->first_name, $response->last_name);
    }

}

Custom helpers can be used for commonly performed tasks. They are mostly helpful in views where you do not want to include business logic. You can create custom functions that format or process the data and return the results

Thanks.

Friday 22 April 2016

Conditionally Loading Service Providers in Laravel 5.1

Hi Everybody,

Today we will discuss about conditionally Loading Service Providers in Laravel 5.1

Since Laravel 5 flattened a lot of the environment-specific structures, much of the configuration that was once stored in different config directories for each environment has now moved into .env files.

But one that can't just live in .env is the environment-dependent loading of service providers.

On a project we're working on, we want to register our error handlers in service providers, and we want to register a different error handler depending on the environment. We have two: ProductionErrorHandler and VerboseErrorHandler, the second of which is for development environments.

Loading service providers normally

In case you're not familiar, defining normal (non-environment-specific) Service Providers happens in /config/app.php. There's a providers array there that looks a bit like this:

    'providers' => [

        /*
         * Laravel Framework Service Providers...
         */
        'Illuminate\Foundation\Providers\ArtisanServiceProvider',
        'Illuminate\Auth\AuthServiceProvider',
        'Illuminate\Bus\BusServiceProvider',
        ...
    ]

So, if your service provider should be loaded in every environment, just toss it into that array and you're good to go.

Loading service providers conditionally

However, if you want to make it conditional, you'll need to head over to /app/Providers/AppServiceProvider.php. This file is the general place you're going to want to be booting and registering anything that's not handled in another service provider, so this is a place you can go to conditionally register your service providers.

Here's what it looks like right now:

<?php namespace app\Providers;

use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }

    /**
     * Register any application services.
     *
     * This service provider is a great spot to register your various container
     * bindings with the application. As you can see, we are registering our
     * "Registrar" implementation here. You can add your own bindings too!
     *
     * @return void
     */
    public function register()
    {
        $this->app->bind(
            'Illuminate\Contracts\Auth\Registrar',
            'App\Services\Registrar'
        );
    }
}

So, let's do our switch.

    // AppServiceProvider.php

    public function register()
    {
        $this->app->bind(
            'Illuminate\Contracts\Auth\Registrar',
            'App\Services\Registrar'
        );

        if ($this->app->environment('production')) {
            $this->app->register('App\Providers\ProductionErrorHandlerServiceProvider');
        } else {
            $this->app->register('App\Providers\VerboseErrorHandlerServiceProvider');
        }
    }
$this->app->register() will set up the service provider just like adding it to config/app.php will, so its register() and boot() methods will get called at the appropriate times.

You could also use switch instead of if, or you could do your work based on other environment variables, or whatever else--but this is your current best bet to conditionally load service providers. Hope this helps!

Thanks.

Friday 15 April 2016

How to implement Model Validation in Laravel 5.1

Hi Everybody,

Model validation is the method of establishing rules to ensure when you’re creating, or updating, an object based on a model, that all of its field values are set appropriately. That all required fields are filled, that all date fields are formatted properly, etc.

We’re going to use the Esensi Model Traits package for model validation.

To install it, open up your app’s composer.json file and add its entry:

  "require": {
    // …
    "esensi/model": "0.5.*"
  }

Next, open the command line, move into your application’s main directory (remember to connect to your virtual machine first if you’re using Homestead), and update Composer to install it:

$ composer update

Finally, to activate the Esensi functionality in the Car model, simply replace:

use Illuminate\Database\Eloquent\Model;

class Car extends Model
// …
with:

use \Esensi\Model\Model;

class Car extends Model
// …
And then you can establish the model’s validation rules by adding a $rules array to the model:

class Car extends Model
{
    protected $rules = [
        'make' => ['required'],
        'model' => ['required'],
    ];
}

The $rules array defines rules for any/all of the model’s fields, and you can use any of Laravel’s built-in validation rules in the individual fields’ rules arrays.

With that established, we can build out the store action in the CarController to handle the Create Car page’s form submissions.

Handling Form Submissions


To start, in the store action, we create a new Car object, populate it with the submitted form data, and then attempt to save it. The save function returns a boolean value, so if it fails — thanks to the Esensi model validation — we can act accordingly, inside that if statement.

And if it succeeds, we can handle that below the if statement (which it will never hit, in that case).

  public function store(Request $request) {
    $car = new \App\Car;

    // populate the model with the form data
    $car->make = $request->make;
    $car->model = $request->model;

    // save the model to create a new object in the database
    if (!$car->save()) {

    }

    // success!
    
  }

Upon failure, we need to: retrieve the validation errors; redirect back to the create page, passing along those errors & the submitted form data (for repopulating the form).

And if it succeeds, we redirect back to the create page (or another page of your choosing), and pass along a “success” message.

Both scenarios are demonstrated here:

  public function store(Request $request) {
    //…
    // save the model to create a new object in the database
    if (!$car->save()) {
      $errors = $car->getErrors();
      return redirect()
            ->action('CarController@create')
        ->with('errors', $errors)
        ->withInput();
    }

    // success!
    return redirect()
      ->action('CarController@create')
      ->with('message', 'Your '. $car->make . ' ' 
                . $car->model . ' has been created!');
  }

Esensi provides the getErrors function to retrieve the validation errors, and then we pass them along via the redirect using the with function.

And Laravel provides the withInput function to pass along all of the form data that was submitted. And thanks to the use of the Forms library’s Form::model function (in the Laravel 5 Application Form Model Binding tutorial) to create a form with model binding, the form will automatically be repopulated without writing any additional code.

Last step: to display those status messages in the view.


Displaying Status Messages

When you pass data during a redirect, it’s “flashed” to the session, meaning it’s only accessible on the next page load. You retrieve session data in Laravel using the session function, passing the key of the object, you’re looking for.

Both the errors object (which contains the validation errors) and the success message were passed using the with function, so you can retrieve both from the session:

      // …
      <div class="page-header">
        <h1>Create a Car</h1>
      </div>

      @if (count(session('errors')) > 0)
      <div class="alert alert-danger">
        @foreach (session('errors')->all() as $error)
          {{ $error }}<br>
        @endforeach
      </div>
      @endif

      @if (session('message'))
      <div class="alert alert-success">
        {{ session('message') }}
      </div>
      @endif

      // …
You call the all function on the errors object to retrieve an array with all the error messages. And then you can just loop through and print out each one, wrapping them in a Bootstrap alert.

And for the success message, we just look for it, and, if found, print it out in another Bootstrap alert.

So now, if you submit the form without all the required values, you’ll see the validation errors appear.



And if you submit the form with all the required data, the car will be created and you’ll see the “success” message.



Thanks.

Friday 8 April 2016

How to add event to different Calendars(Google Calendar, Icalendar, Outlook Calendar, Yahoo Calendar etc.) in Laravel 5.1

Hi Everybody,

Today we will discuss about how to add event to different Calendars(Google Calendar, ICalendar, Outlook Calendar, Yahoo Calendar etc.) in Laravel 5.1

Generally in time event type application we need to add events to different calendars like google calendar,  ICalendar, Outlook Calendar, Yahoo Calendar etc.

In Laravel we will implement it by using below code(in your blade template).

<html>
<head>
    <!-- 1. Include style -->
    <link href="http://addtocalendar.com/atc/1.5/atc-style-blue.css" rel="stylesheet" type="text/css">
</head>
<body>
    <!-- 2. Include script -->
    <script type="text/javascript">(function () {
            if (window.addtocalendar)if(typeof window.addtocalendar.start == "function")return;
            if (window.ifaddtocalendar == undefined) { window.ifaddtocalendar = 1;
                var d = document, s = d.createElement('script'), g = 'getElementsByTagName';
                s.type = 'text/javascript';s.charset = 'UTF-8';s.async = true;
                s.src = ('https:' == window.location.protocol ? 'https' : 'http')+'://addtocalendar.com/atc/1.5/atc.min.js';
                var h = d[g]('body')[0];h.appendChild(s); }})();
    </script>

    <!-- 3. Place event data -->
    <span class="addtocalendar atc-style-blue">
        <var class="atc_event">
            <var class="atc_date_start">2016-05-04 12:00:00</var>
            <var class="atc_date_end">2016-05-04 18:00:00</var>
            <var class="atc_timezone">Europe/London</var>
            <var class="atc_title">Star Wars Day Party</var>
            <var class="atc_description">May the force be with you</var>
            <var class="atc_location">Tatooine</var>
            <var class="atc_organizer">Luke Skywalker</var>
            <var class="atc_organizer_email">luke@starwars.com</var>
        </var>
    </span>
</body>
</html>

In event data write your event detail accordingly.

Thanks.

Friday 1 April 2016

Smooth scroll when click a map marker

Hi Everybody,

Today we will discuss about how to make a smooth scroll when click a map marker.

Html Code

<!DOCTYPE html>
<html lang="en">
<head>
    <script src="https://code.jquery.com/jquery.js"></script>
</head>
<body>
<div id='map_canvas' style="width: 500px;height: 500px"></div>
<div id='1'>
    <h1>1</h1>
    <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

        Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

    </p>
</div>
<div id='2'><h1>2</h1>
    <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

        Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

    </p>

</div>

Jquery Code

<script>
jQuery(function($) {
    // Asynchronously Load the map API
    var script = document.createElement('script');
    script.src = "https://maps.googleapis.com/maps/api/js?v=3.22&callback=initialize";
    document.body.appendChild(script);
});

function attachClickHandler(marker){
google.maps.event.addListener(marker, 'click', function() {

var elem = $(marker.url);
console.log(marker.url);
$('html, body').animate({
scrollTop: elem.offset().top
}, 1000 );

});
}

function initialize() {
var map;
var bounds = new google.maps.LatLngBounds();
var mapOptions = {
mapTypeId: 'roadmap'
};

// Display a map on the page
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
map.setTilt(45);

// Multiple Markers
var markers = [
['London Eye, London', 51.503454,-0.119562, '#1'],
['Palace of Westminster, London', 51.499633,-0.124755, '#2']
];



// Display multiple markers on a map
var infoWindow = new google.maps.InfoWindow(), marker, i;

// Loop through our array of markers & place each one on the map
for( i = 0; i < markers.length; i++ ) {
var position = new google.maps.LatLng(markers[i][1], markers[i][2]);
bounds.extend(position);
marker = new google.maps.Marker({
position: position,
map: map,
title: markers[i][0],
url: markers[i][3]
});
attachClickHandler(marker);
// Automatically center the map fitting all markers on the screen
map.fitBounds(bounds);
}

// Override our map zoom level once our fitBounds function runs (Make sure it only runs once)
var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function(event) {
this.setZoom(14);
google.maps.event.removeListener(boundsListener);
});

}
</script>
</body>
</html>

Thanks