Database: Seeding

To create fake data inside the Database, you can use seeding. All seed classes are stored in the database/seeds directory.

To generate a seeder

php artisan make:seeder UserSeeder

Writing Factories

To get started, take a look at the database/factories/UserFactory.php file in your application.

<?php

use Faker\Generator as Faker;

$factory->define(App\User::class, function (Faker $faker) {
    return [
        'name' => $faker->name,
        'email' => $faker->unique()->safeEmail,
        'password' => '$2y$10$TKh8H1.PfQx37YgCzwiKb.KjNyWgaHb9cbcoQgdIVFlYg7B77UdFm', // secret
        'remember_token' => str_random(10),
    ];
});

$factory->define(App\Test::class, function (Faker $faker) {
    return [
        'name' => $faker->name,
        'user_id' => rand(1,100),                
    ];
});

Using Model Factories

<?php

use Illuminate\Database\Seeder;

class TestSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        factory(App\Test::class, 10)->create();
    }
}

<?php

use Illuminate\Database\Seeder;

class UserSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        factory(App\User::class, 10)->create();
    }
}

Calling Additional Seeders

Within the DatabaseSeeder class, you may use the call method to execute additional seed classes.

<?php

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        //$this->call(TestSeeder::class);
        //$this->call(UserSeeder::class);
        $this->call([
        	TestSeeder::class,
        	UserSeeder::class
        ]);       
    }
}

Running Seeders


php artisan db:seed

or 

php artisan db:seed --class=UserSeeder

Once you have written your seeder, you may need to regenerate Composer’s autoloader using the dump-autoload command:

composer dump-autoload

Middleware

Middleware provide a convenient mechanism for filtering 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.

Whenever there is request by a user then request has to go first on the middleware and when middleware authorized that request then it will go to the backend.

Defining Middleware

cd DirectoryName
php artisan make:middleware MiddlewareName

after creating middleware

<?php

namespace App\Http\Middleware;

use Closure;

class test
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $ip = $request->ip();
        if($ip == '127.0.0.1'){
            throw new \Exception("your IP is correct");            
            //return redirect('/');
        }
        return $next($request);
    }
}

Assigning Middleware To Routes:

Route::get('about', function () {
    return view('about');
})->middleware('test');

Registering Middleware

If you want a middleware to run during every HTTP request to your application, you should first assign the middleware a key in your app/Http/Kernel.php file.

protected $routeMiddleware = [    
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    'test' => \App\Http\Middleware\test::class,
];

Accessors & Mutators

What is accessors

Accessors also called getters are used to format data when you retrieve them from the database.

What is mutators

Mutators also called setters are used to change data before saving data inside the database.so if you want all your emails in your database to be lowercase only, you could do:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class todo extends Model
{
	/* Accessor */
	public function getNameAttribute($value){
		return ucfirst($value);
	}

	/* Mutator */
	public function setEmailAttribute($value)
	{
		$this->attributes['email'] = strtolower($value);
	}
}

Many to Many Relationship

Suppose one user has many roles.
ankur = admin,editor
salman = editor,author
You need to create 3 tables in your Database. users, roles, and role_user. After creating your table, you need to data insert

cd Directory
php artisan tinker
DB::table('users')->insert(['name'=>'Ankur','created_at'=>new DateTime,'updated_at'=>new DateTime])
DB::table('users')->insert(['name'=>'Salman','created_at'=>new DateTime,'updated_at'=>new DateTime])
DB::table('roles')->insert(['role'=>'admin','created_at'=>new DateTime,'updated_at'=>new DateTime])
DB::table('roles')->insert(['role'=>'editor','created_at'=>new DateTime,'updated_at'=>new DateTime])
DB::table('roles')->insert(['role'=>'author','created_at'=>new DateTime,'updated_at'=>new DateTime])
DB::table('role_user')->insert(['role_id'=>'1','user_id'=>'1','created_at'=>new DateTime,'updated_at'=>new DateTime])
DB::table('role_user')->insert(['role_id'=>'2','user_id'=>'1','created_at'=>new DateTime,'updated_at'=>new DateTime])
DB::table('role_user')->insert(['role_id'=>'2','user_id'=>'2','created_at'=>new DateTime,'updated_at'=>new DateTime])
DB::table('role_user')->insert(['role_id'=>'3','user_id'=>'2','created_at'=>new DateTime,'updated_at'=>new DateTime])

Now you have to create model

cd Directory
php artisan make:model user
php artisan make:model role

User model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class user extends Model
{
    public function roles()
    {
    	return $this->belongsToMany(Role::class);        
        
    }   
}

Role model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class role extends Model
{
    public function users()
    {
        return $this->belongsToMany(User::class);
        
    }
}

Retrieve the related record:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\user;

class HomeController extends Controller
{
    public function index(){
    	$roles = user::find(2)->roles;    	
    	//$roles = user::find(2)->roles()->orderBy('role')->get();    	
    	return view('welcome',compact('roles'));
    }
}

One to One Relationship

Suppose You have a users table and passports table. Each user has only one passport number. On this case, you can one to one relationships

cd Directory
php artisan tinker
DB::table('users')->insert(['name'=>Amir,'created_at'=>new DateTime,'updated_at'=>new DateTime])
DB::table('passports')->insert(['number'=>'998787545782','user_id'=>'1','created_at'=>new DateTime,'updated_at'=>new DateTime]);

Now you have to create model for user and passport

cd Directory
php artisan make:model user
php artisan make:model passport

user model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class user extends Model
{
    public function passport(){
    	//return $this->hasOne('App\passport');
    	return $this->hasOne(Passport::class);
    }   
}

passport model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class mobile extends Model
{
    public function user(){
    	return $this->belongsTo(User::class);
    }
}

Retrieve the related record:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\user;

class HomeController extends Controller
{
    public function index(){
    	$passport_data = user::find(1)->passport;    	
    	return view('welcome',compact('passport_data'));
    }
}

Recursive Function

A recursive function is a function that calls itself. If the function keeps calling itself, how does it know when to stop? You set up a condition.

<?php
class Recursion{
	function recursive($num){
		echo $num,"<br/>";
		if(isset($num) && $num < 10){
			return $this->recursive($num + 1);
		}
	}
}
$obj = new Recursion;
$obj->recursive(1);

Traits in PHP

Basically multiple inheritance does not supported by PHP. One class can only extend or inherit from one other class. But there are many cases when you want to extend more than one classes for code reusability. To overcome this problem, as of version 5.4, PHP introduced a new feature of code reuse named trait.

So what are Traits?. Traits are a mechanism for code reuse. A Trait is simply a group of methods that you want include within another class. A Trait, like an abstract class, but It is not allowed to instantiate a trait on its own.

/* mobile.php */

<?php

class Mobile{

	function model(){

		echo "Samsung Galexy 5 <br/>";
	}

}


/* charger.php */

<?php

trait Charger{

	function battery(){

		echo "2500 MP Battery <br/>";
	}

	function power(){

		echo "The Power of Battery 5.5 </br>";
	}


}


/* projector.php */

<?php

trait Projector{

	function range(){

		echo "Projector range 5 meter <br>";
	}

	function power(){

		echo "The Power of Projector Range 2.5<br/>";
	}

	
}


/* body.php */

<?php

trait Body{

	function display(){

		echo "Display 5.5 inc <br/>";
	}

	public $name = "Smart Phone";

	abstract function tabu();
}


/* glass.php */

<?php

include_once('body.php');

trait Glass{

	use Body;

	/*function display(){

		echo "Cornic Gorila Glass <br>";
	}*/
}


/* index.php */

<?php

include_once('mobile.php');
include_once('charger.php');
include_once('projector.php');
include_once('glass.php');


class Samsung extends Mobile{

	use Charger, Projector, Glass{

		Charger::power insteadof Projector;
		Projector::power as Ppower;
	}

	/*function display(){

		echo "This is from index";
	}*/

	function tabu(){

	}
}

$obj = new Samsung;
$obj->model();
$obj->battery();
$obj->range();
$obj->power();
$obj->Ppower();
$obj->display();
echo $obj->name;


Namespace

Normally PHP does not allowed to use same multiple class name or method. So what you do on that situation. You can use Namespace. Namespace just like a virtual directory. You can use same multiple class name or method without a name collision.


/* first.php */
<?php

class A{

	function __construct(){

		echo "I am at global space </br>";
	}
}

/* second.php */
<?php

namespace second;

class A{

	function __construct(){

		echo "I am at second space <br/>";
	}
}


/* index.php */
<?php

include "first.php";
include "second.php";

use second\A;

//$obj = new second\A;	// qualified class name

$obj = new A;		// unqualified class name

$obj = new \A;		// fully qualified class name




Late Static Bindings

The self keyword does not follow the same rules of inheritance. self always resolves to the class in which it is used. This means that if you make a method in a parent class and call it from a child class, self will not reference the child as you might expect.


<?php

class Php{

	public static function framework(){

		echo static::getClass()."<br/>";

	}

	public static function getClass(){

		return __CLASS__;
	}
}

class ChildPhp extends Php{

	public static function getClass(){

		return __CLASS__;
	}
}


$php = new php;
$php->framework();


$childphp = new ChildPhp;
$childphp->framework();

Constant

A constant is declared with the const keyword followed by a name (is not prefixed with a dollar sign like properties).
Syntax: const CONSTANT_NAME
The main difference between properties and constants is that the constant value cannot be changed once it is set.


<?php

/**
 * Area	= π r2
 */

// Procedural way constant define
// define("CONSTANT_NAME", 'value');

class Circle {

	const PI = 3.1415;

	public function area($radius){

		return $radius * $radius * self::PI;
	}
	
}

$circle = new Circle;
echo $circle->area(5);