Saturday, November 21, 2015

Adding localisation to the laravel 5

First, create a new controller "LanguageController". You can use this command : php artisan make:controller LanguageController

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Http\Requests;
use Config;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Session;

class LanguageController extends Controller {

    public function switchLang($lang)
     {
        if (array_key_exists($lang, Config::get('languages'))) {
            Session::set('applocale', $lang);
        }
        return Redirect::back();
     }
}

Ok, as you see we use a custom config array to fetch the available languages of the app, so lets create a languages.php in the config/ directory :
return [
    'en' => 'English',
    'fr' => 'Français',
];
Good! Now to use our controller, we are going to set up one new route:
Route::get('lang/{lang}', ['as'=>'lang.switch', 'uses'=>'LanguageController@switchLang']);
You should now be able to use a Language dropdown (I often put it in my navbar). Check this example based on boostrap dropdown :
<li class="dropdown">
    <a href="#" class="dropdown-toggle" data-toggle="dropdown">
        {{ Config::get('languages')[App::getLocale()] }}
    </a>
    <ul class="dropdown-menu">
        @foreach (Config::get('languages') as $lang => $language)
            @if ($lang != App::getLocale())
                <li>
                    {!! link_to_route('lang.switch', $language, $lang) !!}
                </li>
            @endif
        @endforeach
    </ul>
</li>
Last thing to do is to set up a new Middleware:

// app/Http/Middleware/Language.php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Contracts\Routing\Middleware;
use Illuminate\Foundation\Application;
use Illuminate\Http\Request;
use Illuminate\Routing\Redirector;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Session;

class Language implements Middleware {
    public function handle($request, Closure $next)
    {
        if (Session::has('applocale') AND array_key_exists(Session::get('applocale'), Config::get('languages'))) {
            App::setLocale(Session::get('applocale'));
        }
        else { // This is optional as Laravel will automatically set the fallback language if there is none specified
            App::setLocale(Config::get('app.fallback_locale'));
        }
        return $next($request);
    }
}
And of course we do not forget to update Kernel.php with our new Middleware (check the order I use)

protected $middleware = [
    'Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode',
    'Illuminate\Cookie\Middleware\EncryptCookies',
    'Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse',
    'Illuminate\Session\Middleware\StartSession',
    'App\Http\Middleware\Language',
    'Illuminate\View\Middleware\ShareErrorsFromSession',
    'App\Http\Middleware\VerifyCsrfToken',
];

Friday, November 20, 2015

Configure remote connection to the MongoDB

Check whether you already have Mongodb process listening on the port
netstat -tulpen | grep 017

or
apt-get install procinfo
socklist - display

//Change authorization setting to disabled if you've enabled in
nano /etc/mongod.conf
sudo service mongod restart

Adding database authorisation (RoboMongo failed from Mongodb 3.0)
Creating a new user
cd /usr/bin/mongo to run mongodb shell

use admin
db.createUser( { user: "admin", pwd: "yourpassword", roles: [ { role: "userAdminAnyDatabase", db: "admin" } ] } )

use <databasename>
db.createUser( { user: "accountUser", pwd: "password", roles: [ "readWrite", "dbAdmin" ] } ) 
db.auth("accountUser", "password")
db.getUsers()
db.dropUser(<username>)

//Now enable authorization again and restart the mongodb server


Filter IPTables to allow incoming and outgoing traffic from mongodb server

iptables -L to list the current rules
sudo iptables -L INPUT to see all the input values

iptables -A INPUT -s <ip-address> -p tcp --destination-port 27017 -m state --state NEW,ESTABLISHED -j ACCEPT 

iptables -A OUTPUT -d <ip-address> -p tcp --source-port 27017 -m state --state ESTABLISHED -j ACCEPT

iptables-save to save the rules

then type reboot to restart your terminal and now you'll be able to acces your mongodb



The first rule allows all incoming traffic from <ip-address> on port 27017, which allows the application server to connect to the mongod instance. The second rule, allows outgoing traffic from the mongod to reach the application server.


Lastest MongoDb package on debian is bind to 127.0.0.1, this address doesn’t allow the connection by remote hosts, to change it u must set bind to 0.0.0.0 for eg
root@debian:/var/www# nano /etc/mongodb.conf

bind_ip = 0.0.0.0
port = 27017
root@debian:/var/www/lithium# /etc/init.d/mongodb restart
Done! Remember to secure the connection by password in production mode.

Binding IP
bindip=<youridaddress> and then run the following command.. make sure that /db0 folder is existed

mongod --dbpath /var/lib/mongodb/ --repairpath /var/lib/mongodb/db0
/var/log/mongodb/mongodb.log to see log file if the service can't be started
rm /var/lib/mongodb/mongod.lock to remove the lock file
mongod --repair to repair the service
sudo service mongod restart

Extending Virtual memory in Ubuntu

$ sudo dd if=/dev/zero of=/mnt/swap.0 bs=1024 count=1048576 
$ sudo mkswap /mnt/swap.0 
$ sudo su 
swapon /mnt/swap.0
$ sudo swapon -s

Thursday, November 19, 2015

Fixing Autoload.php error while running projects from Github or others

Warning: require(/opt/lampp/htdocs/laravelprojects/mmdb_web/bootstrap/../vendor/autoload.php): failed to open stream: No such file or directory in /opt/lampp/htdocs/laravelprojects/mmdb_web/bootstrap/autoload.php on line 17

Fatal error: require(): Failed opening required '/opt/lampp/htdocs/laravelprojects/mmdb_web/bootstrap/../vendor/autoload.php' (include_path='.:/opt/lampp/lib/php') in /opt/lampp/htdocs/laravelprojects/mmdb_web/bootstrap/autoload.php on line 17


Use Composer install to update all the dependencies

Friday, November 13, 2015

Using S3 as a storage in Laravel 5

You can view all the regions available for your bucket folder in the following site to put region information in config/filesystem.php

http://www.bucketexplorer.com/documentation/amazon-s3--amazon-s3-buckets-and-regions.html

Add the following line to you s3 config file under confit/filesystem.php. This solve the Curl Error.

'http'    => [    'verify' => 'c:/xampp/php/cacert.pem']

Installing curl on windows

Using aws file storage in Laravel 5 needs curl installed.

Download the package from
http://curl.haxx.se/download.html#Win64

Extract it into c:/curl

Now open the system environment variables and add the c:/curl into the System path.

Fixing URL error 60: SSL certificate problem: unable to get local issuer certificate

Download curl certificate file at
http://curl.haxx.se/ca/cacert.pem

Copy and paste the dowloaded file into c:/xampp/php or whatever your php folder is located.

You certificate file should be located at /opt/lamp/php/cacert.pem if you're using lampstack on linux.

And point your S3 SSL path to the following directory for linux.

S3_SSL_PATH=/opt/lampstack-5.5.31-0/php/cacert.pem


Add the following line into the bottom of the php.ini file
[cURL]
curl.cainfo="C:\xampp\php\cacert.pem"

Including the file in auto load in Laravel 5

Create a new file called helpers.php in App folder and write the following helper functions

<?php
/** * Return sizes readable by humans */function human_filesize($bytes, $decimals = 2){    $size = ['B', 'kB', 'MB', 'GB', 'TB', 'PB'];    $factor = floor((strlen($bytes) - 1) / 3);
    return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) .    @$size[$factor];}
/** * Is the mime type an image */function is_image($mimeType){    return starts_with($mimeType, 'image/');}

 In the autoload section of the composer.json file, add the following lines

"autoload": {
    "classmap": [
        "database"    ],
    "psr-4": {
        "App\\": "app/"    },
    "files": [
        "app/helpers.php"    ]

now go to cmd and write composer dumpauto to regenerate the autoload files. 

Wednesday, November 11, 2015

Running laravel projects on localhost

Firstly, you have to modified your hosts file on windows..


Open the following file with admin rights.
C:\Windows\System32\drivers\etc\hosts

Add whatever site you want to match with localhost

127.0.0.1 yourname.com
localhost yourname.com

Modified httpd-vhosts.conf file from the following folder if you're using xampp for windows

C:\xampp\apache\conf\extra\httpd-vhosts.conf

Add a new virtual host file

<VirtualHost *:80>
    DocumentRoot "C:\xampp\htdocs\laravelprojects\yourproject\public"
    ServerName yourname.com
ServerAlias www.yourname.com
    <Directory "C:\xampp\htdocs\laravelprojects\yourproject\public">
        DirectoryIndex index.php
        AllowOverride All
        Order allow,deny
        Allow from all
    </Directory>
</VirtualHost>

And restart the apache.



Integrating Asgard CMS with laravel 5

Firstly, you've to add several php modules in php.ini file

Uncomment ;ext=php_fileinfo.dll file first where the dependicies to install asgardcms is needed to use that file on windows where PHP in MAC already enabled it.

Now Create a new mysql database to use Asgard CMS.

Now you can create a new asgard cms project by typing

composer create-project asgardcms/platform your-project-name

and then

php artisan asgard:install

to create a new asgard cms project.

Friday, November 6, 2015

Artisan commands

$ php artisan changes

$ php artisan --version

$ php artisan route:list

$ php artisan tinker
> $cat = 'Garfield';
> App\Cat::create(['name' => $cat,'date_of_birth' => new DateTime]);
> echo App\Cat::whereName($cat)->get();
[{"id":"4","name":"Garfield 2","date_of_birth":…}]
> dd(Config::get('database.default'));

Turning the engine off
$ php artisan down

Turning the engine on
$ php artisan up

Optimising and speeding up the application
$ php artisan optimize

Pre-compiling the routes for faster application
$ php artisan route:cache

Generators

• make:command
• make:console
• make:controller
• make:event
• make:middleware
• make:migration
• make:model
• make:provider
• make:request

php artisan make:model Cat
php artisan make:model Cat --no-migration
php artisan make:command --help

CRUD Models

Route-Model binding 

In the RouteServiceProvider.php file, add the following file to link cat
$router->model('cat', 'Furbook\Cat');

Using Forms

In the require section of composer.json, add the following code to use common HTML and form elements and then run composer update

"laravelcollective/html": "5.0.*"

This will install the package. Next, we need to register the service provider and façades. Open config/app.php and add the following the $providers array:

Collective\Html\HtmlServiceProvider::class,

Then add the following two lines to the $alias array:

'Form'      => Collective\Html\FormFacade::class,'Html'      => Collective\Html\HtmlFacade::class,

Create a new controller class from root
php artisan make:controller CatController

Thursday, November 5, 2015

Using MongoDB with laravel 5

pecl install mongodbStep 01

Install MongoDB PHP driver from https://pecl.php.net/package/mongodb
Make sure you use the correct version compatible with both your PHP version and also driver version

Note : Make sure you choose the correct OS .. for example for 64bit you must use x64 edition. ThreadSafe one

Step 02

Extract the folder and Copy the php_mongo.dll from the extracted and paste into php extension folder
C:\xampp\php\ext

Step 03

Now you need to add the php extension. Open php.ini file under C:\xampp\php\ and add the following to the extension group

extension=php_mongo.dll

Then restart your xampp and check phpinfo


If you're working on Linux


Install Mongo DB PHP driver

sudo apt-get install php5-dev php5-cli php-pear
sudo pecl install mongo

or

pecl install mongodb
or
sudo apt-get install php5-mongo (For PHP 5)
sudo apt-get install php-mongodb (for PHP 5.6 or higher)


Building Mongodb driver Manually if the above approach doesn;t work

sudo apt-get install build-essential
apt-get install autoconf
apt-get update
sudo apt-get install libpcre3-dev
pecl install mongodb

Add the following line in php.ini file
extension=mongo.so for (PHP 5.5 or lower)
extension=mongodb.so for (PHP 5.6 or higher)
if you're using nano, you can search using Ctrl + W

To check the path to php.ini file, 
php -i | grep 'Configuration File'
and to see mongo is enabled
php -i | grep 'Mongo'

Configuring Laravel Database to use MongoDB

Modify the database.php under Config file in laravel file structure.

'default' => env('DB_CONNECTION', 'mongodb'),

'mongodb' => [            'driver'   => 'mongodb',            'host'     => env('DB_HOST', 'localhost'),            'port'     => env('DB_PORT', 27017),            'database' => 'eshop',            'username' => '',            'password' => '',//            'username' => env('DB_USERNAME', ''),//            'password' => env('DB_PASSWORD', ''),    '            'charset'  => 'utf8',            'prefix'   => '',
        ],

Create the following php file and then run it, you'll be able to see a new database
<?php$user = array('first_name' => 'MongoDB','last_name' => 'Fan','tags' => array('developer','user'));
// Configuration$dbhost = 'localhost';$dbname = 'testmongo';
// Connect to test database$m = new MongoClient("mongodb://$dbhost");$db = $m->$dbname;
// Get the users collection$c_users = $db->users;
// Insert this new document into the users collection$c_users->save($user);
?>
Now you can install the jenssengers to connect to MongoDB with ORM support
Inside your project root folder, right click and Run Composer here. Then install jenssengers by typing the following composer require jenssegers/mongodb

After the jenssengers installation is done add the followig line inside app.php to start using jenssengers
Jenssegers\Mongodb\MongodbServiceProvider::class, //Mongodb service provider


Now if you want to use model class with your MongodB and not the default one, you should always use the following sample

<?php namespace Furbook;//use Illuminate\Database\Eloquent\Model;use Jenssegers\Mongodb\Model as Eloquent; //Use MongoDB as a model
class Breed extends Eloquent//class Breed extends Model{    public $timestamps = false;    public function cats(){        return $this->hasMany('Furbook\Cat');    }}

You can also include HTML form and views by including the following line in the composer.json required field and run composer update to start using it
"laravelcollective/html": "5.0.*"

and make sure that you're running php artisan db:seed from the project root folder.

Integrating Bootstrap theme on laravel project

Add bootstrap folder "css, js" into Resources folder of the laravel framework

You can just pass the path to the style sheet .
{!! HTML::style('css/style.css') !!}
You can just pass the path to the javascript.
{!! HTML::script('js/script.js'); !!}
Add the following lines in the require section of composer.json file and run composer update"illuminate/html": "5.*".
Register the service provider in config/app.php by adding the following value into the providers array:
'Illuminate\Html\HtmlServiceProvider'
Register facades by adding these two lines in the aliases array:
'Form'=> 'Illuminate\Html\FormFacade', 'HTML'=> 'Illuminate\Html\HtmlFacade'


For the development purpose, you can put all the css and js folders inside public folder and link with asset syntax


<link rel="stylesheet" href="{{ asset('css/bootstrap.css') }}">
<link rel="stylesheet" href="{{ asset('css/bootstrap.min.css') }}">
<link rel="stylesheet" href="{{ asset('css/style.css') }}">


Basic File structures of the laravel 5

routes.php
Located in app -> Http -> routes.php
It define which page to open for the first time. Also the manual link configuration of the whole application

Models
There is no model folder created . So you have to create a new folder "Models" in app folder.


View
View folder is located in Resources->View

Controller
Controller folder is located in app -> http -> controllers

Database Configurations
Database configurations is located in config -> database.php




Installing laravel on windows

If you're on linux, you can follow visit http://tecadmin.net/install-laravel-framework-on-ubuntu/

Step 01 

If you haven't installed xampp server on your PC, you need to download and install first since it offers the full stack for developing PHP web application.

https://downloadsapachefriends.global.ssl.fastly.net/xampp-files/5.6.14/xampp-win32-5.6.14-0-VC11-installer.exe?from_af=true

or

https://bitnami.com/stack/lamp if you're installing for Linux

Step 02

Composer is the basic requirement for laravel development where it handles most of the laravel development dependencies. Download and install the composer with shell menu enabled so that you can run it from right clicking in any windows explorer

https://getcomposer.org/Composer-Setup.exe

or
curl -sS https://getcomposer.org/installer | php
mv composer.phar /usr/local/bin/composer

Step 03

Now it's time to install laravel framework, you can open the composer command prompt by right clicking in any windows explorer and click User composer here and type the following.

composer global require "laravel/installer=~1.1"

Now wait for a few minutes while installing laravel on your PC

Make sure to place the ~/.composer/vendor/bin directory in your PATH so the laravel executable can be located by your system.

Composer Directory is located in
C:\Users\<username>\AppData\Roaming\Composer\vendor\bin

Creating a new laravel application

Now you can create a new laravel project by typing
laravel new blog in the command prompt. This will craft a new laravel application ready to run if you create the folder inside htdocs folder or use composer
composer create-project laravel/laravel your-project-name --prefer-dist

You could use --auth to include the auth scaffoldings in your new project.

Createing a new project with latest laravel version
composer update to update the composer version or

with the version name
composer create-project --prefer-dist laravel/laravel=5.3.* blog
and then
composer update

Now set the application namespace so that it looks niche
php artisan app:name Essentials

Running the test application
Now in your browser, you can type http://localhost/blog/public/ and you will be able to see the crafted laravel application running locally.

If you're running in Ubuntu, you need to give folder permission
sudo chmod 755 -R laravel_project and then

chmod -R o+w laravel_project/storage
composer dump-autoload
or
php artisan cache:clear 
chmod -R 777 app/storage 
composer dump-autoload
For Laravel 5.4 it needs to give 775 or 777 access to bootstrap/cache folder as well
sudo chmod -R 777 bootstrap/cache/