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
Advertisements

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);    
       
        /* If your table name is role_users. So You have to pass your table name as the second parameter */
        //return $this->belongsToMany(Role::class,'role_users');    
    }   
}

Role model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

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

        /* If your table name is role_users. So You have to pass your table name as the second parameter */
        //return $this->belongsToMany(User::class,'role_users'); 
    }
}

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);

Regular Expression

A regular expression is a system used in programming for pattern matching. 
It could be used to text search and replacing. 

/./ Matche each and every single character

/\d+/ Matche any kind of digit one or more

/\w/ Matche anything a-z, 0-9, _

/\s/ Matche every space

/[a-z]+[3-9]+/ Character Set for matching
	example:
		coal547
		goal254		
		Boal
		Poal

/(\.in)?/ Basically it's for optional. Question mark to check whether 
it is or not of the preceding token


Look Around:
------------
? mark is not going to include in the result
= sign is going to match
! sign is not going to match

	example: Lookbehind
		price is $500
		price is €600
		(?<![$])(?<=€)\d+	
		(?<=€)   Positive Lookbehind
		(?<![$]) Negative Lookbehind
	
	example: Lookahead	
		sharthak.com
		harpikpandy.ru
		[a-z]+(?=\.com)
		(?=\.com) Positive Lookahead
		[a-z]{11}(?!\.com)
		(?!\.com) Negative Lookahead


Anchors:
--------
/com$/    $ match at last of the line
/^com/    ^ match at starting point of the line
/com\b/   b/ boundary of the line. it's serach for starting and the end

	example:
		google.com
		com.googula.name


WordPress Information

ওয়ার্ডপ্রেস টার্মিনোলজি

1.slug (mean user friendly url)
2.Template Hierarchy ( ওয়ার্ডপ্রেসে পাট্টিকুলারলি যদি কিছু ফাইল থাকে ওয়ার্ডপ্রেস আগে সেই ফাইলটা দিয়ে কন্টেন্ট দেখায়। যদি ওটা না থাকে তাহলে আরেকটা ফাইল দিয়ে চেক করে যে এ ফাইলটা আছে কিনা তখন সেটা দিয়ে কন্টেন্ট দেখায়। যদি সেটাও না থাকে তাহলে আরেকটা ফাইল দিয়ে কন্টেন্ট দেখায় এভাবে সবশেষে কেউ যদি না থাকে তাহলে index.php দিয়ে কন্টেন্ট দেখায়। এই যে ওর্ডারটা, কন্টেন্ট দেখানোর জন্য কোন টেমপেল্ট ফাইলটা লোড হবে কোন php ফাইলটা লোড হবে। এই ওর্ডারটাকেই বলা হয় Template Hierarchy )

3.Taxonomy And Terms (Categories, Tags)
4.Transient (Temporary Storage)

What is hook?

হুক আসলে জাস্ট একটা ইভেন্ট ব্রডকাস্টিং সিস্টেম। দুই রকমের হুক আছে, অ্যাকশন হুক এবং ফিল্টার হুক

প্লাগেবল ফাংশন কি?

একটা ফাংশনকে এমন ভাবে ডিফাইন করা হয়, যাতে করে ইউজার সেই ফাংশনটি রিরাইট করতে পারে। অথাৎ একটা কন্ডিশনের ভিক্তিতে চেক করা হয় ফাংশনটি লিখা হয়েছে কিনা? যদি না হয় তাহলে ফলবেক হিসেবে কারেন্ট ফাংশনটিকে রির্টান করে। আর যদি থাকে তার মানে সেই existing ফাংশনটিকে নতুন করে লিখা হয়েছে। তখন সে নতুনটাকে রির্টান করে।

Sublime 3


Multiple Same Word Selection:
-----------------------------
select and then ctr+d
 or 
ctr + mouse click 


Code Formating:
---------------
	Menually: Edit > Line > Reindent

	For key set:
		Preferences > key bindings
			[
				{
					"keys" : ["ctrl+shift+r"],
					"command" : "reindent"
				}
			]
	
	or

	when you paste something just do:
	ctrl+shift+v


Sublime Package:
----------------
ctr+shift+p
Install Package
	1. Emmet package
	2. SideBarEnhancements
	3. All AutoComplete
	4. Syntax Highlighting for Sass
	5. CodeFormatter

	
Amazing Emmet for Sublime. Just do it and hit the tab
.container>.row>table.table>(thead>th*3)+(tbody>tr*3>td*3)


Laravel Package:
----------------
ctr+shift+p
Install Package
	1. Blade Snippets
	2. Laravel Blade Highlighter


	
Wordpress Package:
----------------
ctr+shift+p
Install Package
	1. WordPress
	2. WooCommerce Autocomplete
	
	

JQuery Package:
---------------
ctr+shift+p
Install Package	
	1. JQuery