Skip to content

Instantly share code, notes, and snippets.

@MrDavidChz
Last active March 15, 2018 15:18
Show Gist options
  • Save MrDavidChz/0bb92e559352e9fa23781616220c9b0d to your computer and use it in GitHub Desktop.
Save MrDavidChz/0bb92e559352e9fa23781616220c9b0d to your computer and use it in GitHub Desktop.
Laravel

CSV Seeder

Seed your database with CSV files

This package allows CSV based seeds.

Installation

Require this package in your composer.json and run composer update (or run composer require flynsarmy/csv-seeder:1.* directly):

"flynsarmy/csv-seeder": "1.0.*"
[URL GITHUB](https://github.com/Flynsarmy/laravel-csv-seeder)

Usage

Your CSV's header row should match the DB columns you wish to import. IE to import id and name columns, your CSV should look like:

id,name
1,Foo
2,Bar

Seed classes must extend Flynsarmy\CsvSeeder\CsvSeeder, they must define the destination database table and CSV file path, and finally they must call parent::run() like so:

use Flynsarmy\CsvSeeder\CsvSeeder;

class StopsTableSeeder extends CsvSeeder {

	public function __construct()
	{
		$this->table = 'your_table';
		$this->filename = base_path().'/database/seeds/csvs/your_csv.csv';
	}

	public function run()
	{
		// Recommended when importing larger CSVs
		DB::disableQueryLog();

		// Uncomment the below to wipe the table clean before populating
		DB::table($this->table)->truncate();

		parent::run();
	}
}

Drop your CSV into /database/seeds/csvs/your_csv.csv or whatever path you specify in your constructor above.

Examples

<?php

use Illuminate\Database\Seeder;
use Flynsarmy\CsvSeeder\CsvSeeder;
use Carbon\Carbon;
class ExpedienteTableSeeder extends CsvSeeder
{
	public function __construct()
	{
		$this->table = 'expedientes';
		$this->csv_delimiter = '|';
		$this->filename = base_path().'/database/seeds/csvs/expedientes-demo.csv';
		$this->offset_rows = 1;
		$this->mapping = [  
			0 => 'id',
			1 => 'expediente',
			2 => 'descripcion',
			3 => 'status'


		];
		$this->should_trim = true;
	}

    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $this->command->info('Inicio - Creacion de los expedientes  DEMO.');
        DB::statement('SET FOREIGN_KEY_CHECKS=0;');
        // Se realiza un truncate a la tabla en caso que sea necesario
        DB::table($this->table)->truncate();
        // Recomendado cuando importo grandes cantidades de datos
        DB::disableQueryLog();

        
        parent::run();
        //actualizo las fecha de creacion de la base de datos
        DB::table($this->table)->update(['updated_at' => Carbon::now(), 'created_at' => Carbon::now()]);
        DB::statement('SET FOREIGN_KEY_CHECKS=1;');
        $this->command->info('Fin -'.Carbon::now());
    }
}

Add

Within the DatabaseSeeder class, you may use the call method to execute additional seed classes. Using the call method allows you to break up your database seeding into multiple files so that no single seeder class becomes overwhelmingly large. Simply pass the name of the seeder class you wish to run:

<?php

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(AgenciasTableSeeder::class);
         $this->call(CatAduanasTableSeeder::class);
         $this->call(CatTipoPagosTableSeeder::class);
         $this->call(CatUsertypeTableSeeder::class);
         $this->call(EmpresasTableSeeder::class);
         $this->call(ExpedienteTableSeeder::class);
         $this->call(UsuariosSystemTableSeeder::class);


        Model::reguard();
    }

}

Running Seeders

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

composer dump-autoload

Run Seeders

php artisan db:seed

Run only Seeder

php artisan db:seed --class=UsersTableSeeder

Run migration and seders

php artisan migrate:refresh --seed

Laravel Collective

creation of forms with LaravelCollective

URL documentation

https://laravelcollective.com/docs/5.4/html

Installation LaravelCollective

composer require "laravelcollective/html":"^5.4.0"

Commands Laravel

New Project

composer create-project --prefer-dist laravel/laravel <nombre>
php artisan serve

Migration DataBase

php artisan make:migration --help
php artisan make:migration  create_products_table --create=products
php artisan make:migration alter_products_Table --table=products
php artisan migrate

Restart Migration

php artisan migrate:refresh
php artisan migrate:refresh --seed

Model & Migration laravel

php artisan make:model Products -m

Routes List

php artisan route:list

Tinker

Docs = http://laravel.com/docs/5.4/eloquent-collections#available-methods
php artisan tinker
$user = ['name' => 'Davis', 'email'=>'[email protected]','password'=>bcrypt('123456')];
\App\User::create($user);
\App\User::all();

Create Controller

php artisan make:controller ExampleController

Create Seeder

php artisan make:seeder UserTableSeeder

Execute Seeder

php artisan db:seed

Queries

Validate if the commands apply for new versions of laravel

Model::

Select
  select('col1','col2')
  ->select(array('col1','col2'))
  ->select(DB::raw('businesses.*, COUNT(reviews.id) as no_of_ratings, IFNULL(sum(reviews.score),0) as rating'))  
  ->addSelect('col3','col4')
  ->distinct() // distinct select
  
From
  ->from('table')
  ->from(DB::raw('table, (select @n :=0) dummy'))
  ->from(DB::raw("({$subQuery->toSql()}) T ")->mergeBindings($subQuery->getQuery())

  
Query
  ->where('column','value')
  ->where('column','LIKE','%'.$value.'%')
  ->where(function ($query) {
  	$query->where('a', '=', 1)
    	->orWhere('b', '=', 1);
  })
  ->orWhere('column','!=', 'value')
  ->whereRaw('age > ? and votes = 100', array(25))
  
  ->whereRaw(DB::raw("id in (select city_id from addresses GROUP BY addresses.city_id)"))
  
  ->whereExists(function($query)
  {
  	$query->select(DB::raw(1))
        ->from('business_language')
        ->whereRaw('business_language.language_id = languages.id')
        ->groupBy('business_language.language_id')
        ->havingRaw("COUNT(*) > 0");
  })
  ->orWhereExists()
  ->whereNotExists()
  ->orWhereNotExists()
  
  ->whereIn('column',[1,2,3])
  ->orWhereIn()
  ->whereNotIn('id', function($query){
    $query->select('city_id')
    ->from('addresses')
    ->groupBy('addresses.city_id');
  })
  ->whereNotIn()
  ->orWhereNotIn
  
  ->whereNull('column') //where `column` is null
  ->orWhereNull('column') //or where `column` is null
  ->whereNotNull('column')  //where `column` is not null 
  ->orWhereNotNull('column')  //or where `column` is not null 
  
  ->whereDay()
  ->whereMonth('column', '=', 1) //
  ->whereYear('column', '>', 2000) //uses sql YEAR() function on 'column'
  ->whereDate('column', '>', '2000-01-01')
  
Joins
  ->join('business_category','business_category.business_id','=','businesses.id')
  ->leftJoin('reviews','reviews.business_id', '=', 'businesses.id')
  ->join('business_category',function($join) use($cats) {
    $join->on('business_category.business_id', '=', 'businesses.id')
    ->on('business_category.id', '=', $cats, 'and', true);
  })
  ->join(DB::raw('(SELECT *, ROUND(AVG(rating),2) avg FROM reviews WHERE rating!=0 GROUP BY item_id ) T' ), function($join){
  	$join->on('genre_relation.movie_id', '=', 'T.id')
  })
  
Eager Loading 
  ->with('table1','table2')
  ->with(array('table1','table2','table1.nestedtable3'))
  ->with(array('posts' => function($query) use($name){
    $query->where('title', 'like', '%'.$name.'%')
      ->orderBy('created_at', 'desc');
  }))
  
  
Grouping
  ->groupBy('state_id','locality')
  ->havingRaw('count > 1 ')
  ->having('items.name','LIKE',"%$keyword%")
  ->orHavingRaw('brand LIKE ?',array("%$keyword%"))
				
Cache
  ->remember($minutes)
  ->rememberForever()
    
Offset & Limit
  ->take(10)
  ->limit(10)
  ->skip(10)
  ->offset(10)
  ->forPage($pageNo, $perPage)
  
Order
  ->orderBy('id','DESC')
  ->orderBy(DB::raw('RAND()'))
  ->orderByRaw('type = ? , type = ? ', array('published','draft'))
  ->latest() // on 'created_at' column
  ->latest('column')
  ->oldest() // on 'created_at' column
  ->oldest('column')
  
Create
  ->insert(array('email' => '[email protected]', 'votes' => 0))
  ->insert(array(   
    array('email' => '[email protected]', 'votes' => 0),
    array('email' => '[email protected]', 'votes' => 0)
  )) //batch insert
  ->insertGetId(array('email' => '[email protected]', 'votes' => 0)) //insert and return id
  
Update
  ->update(array('email' => '[email protected]'))
  ->update(array('column' => DB::raw('NULL')))
  ->increment('column')
  ->decrement('column')
  ->touch() //update timestamp
  
Delete
  ->delete()
  ->forceDelete() // when softdeletes enabled
  ->destroy($ids) // delete by array of primary keys
  ->roles()->detach() //delete from pivot table: associated by 'belongsToMany'
  
  
Getters
  ->find($id)
  ->find($id, array('col1','col2'))
  ->findOrFail($id)
  ->findMany($ids, $columns)
  ->first(array('col1','col2'))
  ->firstOrFail()
  ->all()
  ->get()
  ->get(array('col1','col2')) 
  ->getFresh() // no caching
  ->getCached() // get cached result
  ->chunk(1000, function($rows){
  	$rows->each(function($row){
  		
  	});
  })
  ->lists('column') // numeric index
  ->lists('column','id') // 'id' column as index
  ->lists('column')->implode('column', ',') // comma separated values of a column
  ->pluck('column')  //Pluck a single column's value from the first result of a query.
  ->value('column')  //Get a single column's value from the first result of a query.
  
Paginated results
  ->paginate(10)
  ->paginate(10, array('col1','col2'))
  ->simplePaginate(10)
  ->getPaginationCount() //get total no of records
  
Aggregate
  ->count()
  ->count('column')
  ->count(DB::raw('distinct column'))
  ->max('rating')
  ->min('rating')
  ->sum('rating')
  ->avg('rating')
  ->aggregate('sum', array('rating')) // use of aggregate functions
  
Others
  ->toSql() // output sql query
  ->exists() // check if any row exists
  ->fresh() // Return a fresh data for current model from database
  
Object methods
  ->toArray() //
  ->toJson()
  ->relationsToArray() //Get the model's relationships in array form.
  ->implode('column', ',') // comma separated values of a column
  ->isDirty()
  ->getDirty() //Get the attributes that have been changed but not saved to DB
  
 Debugging
DB::enableQueryLog();
DB::getQueryLog();
Model::where()->toSql() // output sql query

Laravel

Instalar Laravel en Ubuntu

Requisitos previos:

Tener al menos instalado PHP y un motor de base de datos como por ejemplo MySQL. También se recomienda instalar un servidor web como por ejemplo Apache o Nginx.

Paso 1: Instalar CURL

$ sudo apt-get install curl

Paso 2: Instalar composer de forma global

$ curl -sS https://getcomposer.org/installer | php

Este comando descargará en nuestra carpeta home el archivo composer.phar. Este archivo será llamado cada vez que queramos usar composer, así que vamos a instalarlo de forma global para que podamos usar composer desde cualquier directorio.

Para instalar composer de manera global debemos mover el archivo composer.phar a la carpeta /usr/local/bin, ejecutaremos el siguiente comando:

$ sudo mv ~/composer.phar /usr/local/bin/composer

Una vez hecho esto podemos ejecutar en la terminal el comando composer.

Paso 3: Instalar laravel

Tenemos 2 formas de instalar laravel, una es a través del instalador de Laravel y la otra es utilizando Composer Create-Project (Recomendada).

a) Vía el instalador de Laravel

Descargar el instalador de Laravel usando composer:

$ composer global require "laravel/installer"

Ahora debemos modificar el PATH para que el sistema pueda reconocer los comandos de Laravel, esto se hace modificando el archivo .profile ó en .bashrc. Abrimos el archivo .profile:

$ sudo vim ~/.profile

Vamos al final del archivo y agregamos la siguiente línea:

Para Ubuntu 14.04

PATH="$PATH:~/.composer/vendor/bin"

Para Ubuntu 16.04

PATH="$PATH:~/.config/composer/vendor/bin"

Guardamos el archivo.

Ahora ejecutamos el siguiente comando:

$ composer global update

Para que reconozca el comando debemos cerrar la terminal.

De esta forma realizamos una instalación global de Laravel en nuestro equipo.

Para crear un proyecto:

$ laravel new {nombre_proyecto}

Ejemplo:

laravel new blog

b) Via Composer Create-Project

Ir al directorio donde alojas tus proyectos (por ejemplo: /var/www/) y en la terminal ejecuta el siguiente comando:

$ composer create-project laravel/laravel nombre_proyecto

Instalar una versión especifica de Laravel con composer create-project

$ composer create-project laravel/laravel myproject --prefer-dist v5.1.8

Otro ejemplo de uso:

$ composer create-project laravel/laravel myproject --prefer-dist v5.1.*

Nota: Si no instalaste composer de manera global tendrás que ejecutar php composer.phar y necesitaras tener el archivo composer.phar en la misma carpeta desde donde vas a ejecutar el comando.

Nota2: Si quieres usar los comandos de laravel es necesario también instalar Laravel de forma global

Verificar la versión instalada del framework

Cambiar de directorio a la raiz del framework y ejecutar el siguiente comando:

$ php artisan --version

Servidor Web

Podemos hacer uso del servidor web de pruebas que trae Laravel. Para hacer esto, desde la terminal nos cambiamos al directorio del proyecto y ejecutamos el siguiente comando:

$ php artisan serve

salida:

Laravel development server started on http://localhost:8000/

Ahora podemos acceder al proyecto desde el navegador ingresando http://localhost:8000/

Pro Tip:

Servidor Web Apache

Debes habilitar el mod_rewrite, para poder activarlo, en la terminal ejecutar:

$ sudo a2enmod rewrite

Para que los cambios hagan efecto, reiniciar el apache:

$ service apache2 restart

Y Crear un virtualhost que apunte a la carpeta public que se encuentra en la raíz del proyecto.

A las carpetas bootstrap y storage dar propietario y grupo www-data (Esto aplica para apache y nginx):

$ sudo chown -Rvf www-data:www-data bootstrap
$ sudo chown -Rvf www-data:www-data storage

Artisan

Listar todos los comandos habilitados

$ php artisan list

Ver versión

$ php artisan --version

Crear un controlador

Primero que todo debemos ubicarnos en el directorio del proyecto.

$ php artisan make:controller EjemploController

Salida:

Controller created successfully.

Este comando creará un controlador en el directorio app/Http/Controllers/

Crear componente Seeder

$ php artisan make:seeder UserTableSeeder

Realizar migración y ejecutar los seeders

$ php artisan migrate --seed

Rollback de seeders

Esto va a eliminar las tablas, luego las va a volver a crear y finalmente va a crear el seeder de usuario:

$ php artisan migrate:refresh --seed

Ejecutar seeders

$ php artisan db:seed

Sistema de Autenticación Laravel

Laravel 5.2 tiene dos clases listas para migrar, estas son: CreateUsersTable y CreatePasswordResetsTable y se encuentran en database/migrations/

Definiremos los datos de conexión en el archivo de configuración .env

Ejemplo:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=blog
DB_USERNAME=root
DB_PASSWORD=dev

Ahora reiniciamos el servidor web

ctrl + c
$ php artisan serve

y limpiamos la configuración en cache

$ php artisan config:clear

Para migrar las tablas ejecutaremos el siguiente comando:

$ php artisan migrate

Ahora crearemos las vistas de autenticación que provee laravel

$ php artisan make:auth
Created View: /Users/andres/Sites/blog/resources/views/auth/login.blade.php
Created View: /Users/andres/Sites/blog/resources/views/auth/register.blade.php
Created View: /Users/andres/Sites/blog/resources/views/auth/passwords/email.blade.php
Created View: /Users/andres/Sites/blog/resources/views/auth/passwords/reset.blade.php
Created View: /Users/andres/Sites/blog/resources/views/auth/emails/password.blade.php
Created View: /Users/andres/Sites/blog/resources/views/layouts/app.blade.php
Created View: /Users/andres/Sites/blog/resources/views/home.blade.php
Created View: /Users/andres/Sites/blog/resources/views/welcome.blade.php
Installed HomeController.
Updated Routes File.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment