How to use form validation in laravel

Laravel

Posted on 21 May 15 by Vickey

We have inbuilt validation in laravel by using the laravel validation we can validate our form very easily In this tutorial i have a form which have name and email and password fields for validate this form i use the below code

$userdata = array(

  'name' => Input::get('name'),
  'email' => Input::get('email'),
 'password' => Input::get('password'),

);

$rules = array(
    'name'=>'required|alpha_num|min:5',
       'email'=>'required|unique:users,email|email',
      'password'=>'required|alpha_num|min:5'
);

$validator = Validator::make($userdata, $rules);

if($validator->fails())
{ 
    return Redirect::back()->withInput()->withErrors($validator);
}
else{
              // save record in databse

}

for show validation message on view use

     @if($errors->any())

        {{ implode ('', $errors->all('<p><strong>:message</strong></p>'))}}

    @endif

How to render a view without controller in laravel

Laravel

Posted on 21 May 15 by Vickey

Render a view without controller in laravel

Route::get('home', function()
{
    return View::make('home.index')->with('subjects', subject::all());
});

you can use this in a small projects but if your projects is big then you need to create controller

Database engines in mysql

Mysql

Posted on 21 May 15 by Vickey

Here is the list of database engines supported by mysql

MyISAM

InnoDB

Memory

CSV

Merge

Archive

Federated

Blackhole

InnoDB is the defualt storage engine in version 5.5 before version 5.5 MyISAM was default engine

MyISAM: The table size limit of Myisam engine is 256TB. On startup MySQL inspections MyISAM tables pertaining to corruption as well as mend all of them in the event of mistakes. MyIsam engine does not support transactions.mostly this is used in Web, data warehousing.

InnoDB: This engine support transactions and it support crash recuperation in addition to multi-version concurrency control. This engine engine provides foreign key referential integrity constraint. The table size limit of InnoDB engine is 64TB.

Memory: This engine also known as heap. This engine create tables on memory and the lifetime of tables depends on server and when server restarted data lost because it creates temporary tables for quick lookups

CSV: In this engine data store in a csv file. This is very flexible in this format data is easily integrated with other applications.This engine does not support null data type

Merge: This engine combine multiple tables which have same structure. This is known as MRG_MyISAM.By using merge table we can increase speed by joining multiple tables. It allow only select update insert delete operations on merge table. if you use drop table then this will remove only merge specification.

Archive: This can store large number of record.when a record is inserted in it compress it and on reading decompress by using zlib library.This engine only allow insert and delete operation.

Federated: This engine manage data from a remote server and no data store in locally.When we use query on local server it automatically execute on remote server.

Blackhole: This engine accept data but not store.this used for testing purpose.

How to use Blowfish password hasher in cakephp

Cakephp

Posted on 13 May 15 by Vickey

Blowfish password hasher is very strong. it is very difficult to hack. you can use blowfish hasher by following these steps.

In your model add this code

public function beforeSave($options = array()) {

        if (isset($this->data[$this->alias]['password'])) {
            $passwordHasher = new BlowfishPasswordHasher();
            $this->data[$this->alias]['password'] = $passwordHasher->hash(
                $this->data[$this->alias]['password']
            );
        }

        return parent::beforeSave($options);
    }

it will hash your password before save record

and for use blowfish hash password add this in auth component

public $components = array('Session', 'Cookie',
    'Auth' => array(

                'authenticate' => array(
                    'Form' => array(
                            'passwordHasher' => 'Blowfish',
                            'userModel' => 'User',
                            'fields' => array(
                            'username' => 'username',
                            'password' => 'password'
                        )
                    )
                )

    ),
);

How to use alternate row color in a html table

Js

Posted on 13 May 15 by Vickey

For showing each row different we can use alternate row color in a table. For give different color we need to add a differnt style or different backgrownd color here is a way to give different background color to alternate rows In this example i have a table with id "diffcolor".

<table style="width:100%" id="diffcolor">
  <tr>
    <td>Jack</td>
    <td>Smith</td> 
    <td>50</td>
  </tr>
  <tr>
    <td>Paul</td>
    <td>Jackson</td> 
    <td>94</td>
  </tr>
    <tr>
    <td>Alen</td>
    <td>Smith</td> 
    <td>50</td>
  </tr>
      <tr>
    <td>Jill</td>
    <td>Smith</td> 
    <td>50</td>
  </tr>
        <tr>
    <td>Bob</td>
    <td>Joy</td> 
    <td>50</td>
  </tr>
</table> 

here is js function for add different background color to the alternate rows

function tableRowColor(id){
  if(document.getElementsByTagName){
    var table = document.getElementById(id);
    var rows = table.getElementsByTagName("tr");
    for(i = 0; i < rows.length; i++){
      if(i % 2 == 0){
        rows[i].className = "even";
      }else{
        rows[i].className = "odd";
      }
    }
  }
}

and now we need to call this function and pass table id

tableRowColor('diffcolor');

this function will add different class on table's rows now we need to give style

   .even{
    background: #f2f2f2;
   }
   .odd{
    background: #fff;
   }

How to seeding database in laravel5

Laravel

Posted on 08 May 15 by Vickey

When we create a webapplication we need test data in our database for building the frontend.laravel provide us to generate test data in our database. we have inbuilt database seeding in laravel. In this tutorial i am using laravel5. so if you have done with migration then you can seed your databse. Lets start first go to directory laravel5/database/seeds and here you can see a file name as DatabaseSeeder.php open it and you will see the below code

use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;

class DatabaseSeeder extends Seeder {

    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        Model::unguard();

        //$this->call('UserTableSeeder');
    }

}

uncomment this code $this->call('UserTableSeeder');

class DatabaseSeeder extends Seeder {

    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        Model::unguard();

        $this->call('UserTableSeeder');
    }

}

now create a new file UserTableSeeder.php in same directory and add the below code

use App\User;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Eloquent\Model;

class UserTableSeeder extends Seeder {

    public function run()
    {
        DB::table('users')->delete();

        $user = User::create(array(
            'name' => 'philipbrown',
            'email' => 'name@domain.com',
            'password' => 'qwerty'
        ));
    }

}

here i am seeding users table. if you want to add more testing data you can use Faker. to install faker add this in composer.json file

"require-dev": {
  "fzaninotto/faker": "1.3.*@dev"
},

and update composer by running command

composer update

and replace this below code in UserTableSeeder.php

class UserTableSeeder extends Seeder {

    public function run()
    {
        DB::table('users')->delete();
        $faker = Faker\Factory::create();
        for ($i = 0; $i < 100; $i++)
        {
            $user = User::create(array(
                'name' => $faker->name,
                'email' => $faker->email,
                'password' => $faker->word
          ));
        }
    }
}

when you have done run command in your terminal

php artisan db:seed

it will seed all seeder files if you want only one you can use

php artisan db:seed --class=UserTableSeeder

in case if you face error like "[ReflectionException] Class UserTableSeeder does not exist" then you need run command

composer dump-autoload

and now again run

php artisan db:seed --class=UserTableSeeder

you can see your test data in your users table

Thanks

How to change defualt login redirect in laravel5

Laravel

Posted on 07 May 15 by Vickey

when you login with the defualt login of laravel5 it will redirect to /home but if you want to change this follow these steps

Go to directory

laravel5/vendor/laravel/framework/src/Illuminate/Foundation/Auth

Open file AuthenticatesAndRegistersUsers.php and search this

public function redirectPath()
{
    if (property_exists($this, 'redirectPath'))
    {
        return $this->redirectPath;
    }

    return property_exists($this, 'redirectTo') ? $this->redirectTo : '/home';
}

here you can change your custom path like this

public function redirectPath()
{
    if (property_exists($this, 'redirectPath'))
    {
        return $this->redirectPath;
    }

    return property_exists($this, 'redirectTo') ? $this->redirectTo : '/dashboard';
}

How to create or install login and registration functionality on laravel5

Laravel

Posted on 07 May 15 by Vickey

In laravel5 we have inbuilt login and regitration functionality for login page we have url example.com/public/auth/login and for signup page example.com/public/auth/register but in fresh copy of laravel this will not work properly because we need to migrate our database first so lets start step by step

First create a databse for this application here i am creating a databse name as laravel5

Go to directory /your laravel root folder/config/ and open file database.php and find this

    'mysql' => [
        'driver'    => 'mysql',
        'host'      => env('DB_HOST', 'localhost'),
        'database'  => env('DB_DATABASE', 'forge'),
        'username'  => env('DB_USERNAME', 'forge'),
        'password'  => env('DB_PASSWORD', ''),
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
        'strict'    => false,
    ],

and put your actual details of your databse and server and save your file

    'mysql' => [
        'driver'    => 'mysql',
        'host'      => env('DB_HOST', 'localhost'),
        'database'  => env('DB_DATABASE', 'laravel5'),
        'username'  => env('DB_USERNAME', 'root'),
        'password'  => env('DB_PASSWORD', ''),
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
        'strict'    => false,
    ],

let me know you that i am using operationg system ubuntu and webserver is xampp

Now open your terminal window by pressing Ctrl+Alt+t and locate in your laravel root directory

ubuntu@ubuntu-System:~$ cd /opt/lampp/htdocs/laravel5

now run

sudo /opt/lampp/bin/php artisan migrate:install

if you installed php globally then

sudo php artisan migrate:install

after complete the command you will see message in your terminal "Migration table created successfully. " and now you can see a table name as "migrations" in your databse.

if you will open directory laravel5/database/migrations you can see migration files for users and password reset table so there is no need to create new file for users now run command

sudo /opt/lampp/bin/php artisan migrate

you will see conform messege "Do you really wish to run this command? [y/N]" put here "yes" and your tables will be create you can check your databse now you can register and login with your database tables.

What is interface in php

php

Posted on 06 May 15 by Vickey

Interface is a class or we can say base class which is implement in a child calss. We defined interface by using keyword interface. all method or function of a interface should be public according the nature of interface.Function in interface does not have any functionality these are overwride in child class and these are necessary to use child class

interface setTemplate
{
    public function setVar($var);
    public function getVar($var);
}

class template implements setTemplate{

    fuction setVar($var){

        function body.......

    }

    fuction getVar($var){

        function body.......

    }
}

if we does not use all function of a interface then it will give erorr

class template implements setTemplate{

    fuction setVar($var){

        function body.......

    }
}

the above code will return error

like abstract class we can create object of a interface we only implement it in a child class

Abstract class in php

php

Posted on 02 May 15 by Vickey

As you know the meaning of abstract is hidden or unvisiable yes the role of abstract classes are same. abstract class can not initialized directoly or we can say that we can not create object of abstract classes. we always use abstract class as a base class and inherit in a child class. In abstract class at least one function should be abstract. we can in inherit an abstract calss in another abstract class we can create abstract class by adding abstract keyword before class keyword.

abstract class mybaseclass(){

    abstract protected function sum($a,$b){

    }
}

we can declare abstract function in child class

class mychildclass extends mybaseclass(){

        protected function sum($a,$b){
          $sum=$a+$b;
      echo $sum;
       }
}