Sintek Ong

Sintek Ong

1560413313

Make your Laravel Seeder Using Model Factories

You must have just started development of a Laravel based project and you need to fill it with data. Laravel includes a simple method of seeding your database with test data using seed classes. All seed classes are stored in the database/seeds directory…

Database Seeding is important when developing applications whether it’s going to be a small app or a large scale application.

Writing Seeders and Model Factories

Table of Contents

  • Pratical Example
  • Generating Model and Migration
  • Write Migration and Model Factory
  • Generating Seeder
  • Write Database Seeder
  • Conclusion

To create a Seeder the make:seeder artisan command is executed. Read Laravel docs here for more instructions

php artisan make:seeder TestSeeder

A model Factory is generated by executing the make:factory artisan command.

php artisan make:factory PostFactory --model=Post

Read more here about using model factories in Laravel.

Pratical Example

Let’s seed a simple Film sharing and commenting application, where users can share films belonging to a particular genre. So there will be a User, Film, Comment and Genre Model .

Generating Model and Migration

Laravel default comes with a User model and migration which is good enough for this example. Let’s go ahead and create the other models and migration.

php artisan make:model Film -m 
 ## create film model and migration

php artisan make:model Comment -m 
 ## create comment model and migration

php artisan make:model Genre -m
 ## create genre model and migration

Write Migration and Model Factory

User migration and model factory comes prewritten … so we can skip …

Write Genre Migration and Factory

// Genre Migration
   public function up()
    {
        Schema::create('genres', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->timestamps();
        });
    }

php artisan make:factory GenreFactory --model=Genre

// Genre Factory
<?php

use Faker\Generator as Faker;

$factory->define(App\Genre::class, function (Faker $faker) {
    return [
        'name' => $faker->word,
    ];
});

Write Film Migration and Factory

//Film Migration 
public function up()
    {
        Schema::create('films', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id');
            $table->string('title');
            $table->text('description');
            $table->date('release_date');
            $table->enum('rating',[ 1, 2, 3, 4, 5] );
            $table->integer('genre_id');
            $table->string('photo');
            $table->string('slug');
            $table->timestamps();

        });
    }

php artisan make:factory FilmFactory --model=Film

<?php

use Faker\Generator as Faker;

$factory->define(App\Film::class, function (Faker $faker) {
    return [
        'title' => $faker->sentence(5),
        'description' => $faker->realText(rand(80, 600)),
        'release_date'  => $faker->date(),
        'rating' => rand(1,5),
        'genre_id' => function () {
            // Get random genre id
            return App\Genre::inRandomOrder()->first()->id;
        },
        'photo'  => 'https://via.placeholder.com/350x150',
        'slug'   => str_replace('--', '-', strtolower(preg_replace('/[^a-zA-Z0-9]/', '-', trim($faker->sentence(5))))),
    ];
});

*Write Comment Migration and Factory *

// Comment Migration
    public function up()
    {
        Schema::create('comments', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id');
            $table->integer('film_id');
            $table->text('comment');
            $table->timestamps();
        });
    }

php artisan make:factory CommentFactory --model=Comment

<?php

use Faker\Generator as Faker;

$factory->define(App\Comment::class, function (Faker $faker) {
    return  [
        'comment' => $faker->realText(rand(10, 300)),
      ];
});

Generating Seeder

Write Genre Seeder

php artisan make:seeder GenreTableSeeder

public function run()
    {
        // How many genres you need, defaulting to 10
        $count = (int)$this->command->ask('How many genres do you need ?', 10);

        $this->command->info("Creating {$count} genres.");

        // Create the Genre
        $genres = factory(App\Genre::class, $count)->create();

        $this->command->info('Genres Created!');

    }

Write User and Film Seeder

php artisan make:seeder UserFilmSeeder

Since this is a film sharing application, every user tends to share a certain number of film on this app. So our seeder should look like …

public function run()
    {
        // How many genres you need, defaulting to 10
        $userCount = (int)$this->command->ask('How many users do you need ?', 10);

        // Ask range for film per user needed
        $r = 0 . '-' . 10;
        $filmRange = $this->command->ask('How many films per user do you need ?', $r);

        $this->command->info("Creating {$userCount} users each having a film range of {$filmRange}.");

        // Create the Users 
        $users = factory(App\User::class, $userCount)->create();

        // Create a range of films for each users
        $users->each(function($user) use ($filmRange){
            factory(App\Film::class, $this->count($filmRange))
                    ->create(['user_id' => $user->id]);
        });

        $this->command->info('Users and Films Created!');

    }

     // Return random value in given range
    function count($range)
    {
        return rand(...explode('-', $range));
    }

Write Comment Seeder

php artisan make:seeder CommentTableSeeder

public function run()
    {
        $r = 0 . '-' . 10;
        $commentRange = $this->command->ask('How many comments per film do you need ?', $r);

        $films = App\Film::all();

        $this->command->info("Creating a range of {$commentRange} comments for {$films->count()} films .");

        $films->each(function($film) use ($commentRange){
            factory(App\Comment::class, $this->count($commentRange))
                ->create([
                       'film_id' => $film->id,
                       'user_id' => App\User::all()->random()->id
                    ]);
        });

        $this->command->info('Comments Created!');

    }

      // Return random value in given range
    function count($range)
    {
        return rand(...explode('-', $range));
    }

Write Database Seeder

Let’s invoke generated seeders in the DatabaseSeeder class using the call method

<?php

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{

    public function run()
    {
        Eloquent::unguard();

        // Ask for db migration refresh, default is no
        if ($this->command->confirm('Do you wish to refresh migration before seeding, it will clear all old data ?')) {

            // Call the php artisan migrate:fresh using Artisan
            $this->command->call('migrate:fresh');

            $this->command->line("Database cleared.");
        }

        $this->call(GenreTableSeeder::class);
        $this->call(UserFilmSeeder::class);
        $this->call(CommentTableSeeder::class);

        $this->command->info("Database seeded.");

        // Re Guard model
        Eloquent::reguard();

    }
}

Conclusion

If you run php artisan db:seed it will ask questions and seed the data accordingly.

#laravel #php

What is GEEK

Buddha Community

Make your Laravel Seeder Using Model Factories
Seamus  Quitzon

Seamus Quitzon

1595201363

Php how to delete multiple rows through checkbox using ajax in laravel

First thing, we will need a table and i am creating products table for this example. So run the following query to create table.

CREATE TABLE `products` (
 `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
 `name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
 `description` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
 `created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
 `updated_at` datetime DEFAULT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci

Next, we will need to insert some dummy records in this table that will be deleted.

INSERT INTO `products` (`name`, `description`) VALUES

('Test product 1', 'Product description example1'),

('Test product 2', 'Product description example2'),

('Test product 3', 'Product description example3'),

('Test product 4', 'Product description example4'),

('Test product 5', 'Product description example5');

Now we are redy to create a model corresponding to this products table. Here we will create Product model. So let’s create a model file Product.php file under app directory and put the code below.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    protected $fillable = [
        'name','description'
    ];
}

Step 2: Create Route

Now, in this second step we will create some routes to handle the request for this example. So opeen routes/web.php file and copy the routes as given below.

routes/web.php

Route::get('product', 'ProductController@index');
Route::delete('product/{id}', ['as'=>'product.destroy','uses'=>'ProductController@destroy']);
Route::delete('delete-multiple-product', ['as'=>'product.multiple-delete','uses'=>'ProductController@deleteMultiple']);

#laravel #delete multiple rows in laravel using ajax #laravel ajax delete #laravel ajax multiple checkbox delete #laravel delete multiple rows #laravel delete records using ajax #laravel multiple checkbox delete rows #laravel multiple delete

I am Developer

1597487833

Country State City Drop Down List using Ajax in Laravel

Here, i will show you how to create dynamic depedent country state city dropdown list using ajax in laravel.

Country State City Dropdown List using Ajax in php Laravel

Follow Below given steps to create dynamic dependent country state city dropdown list with jQuery ajax in laravel:

  • Step 1: Install Laravel App
  • Step 2: Add Database Details
  • Step 3: Create Country State City Migration and Model File
  • Step 4: Add Routes For Country State City
  • Step 5: Create Controller For Fetch Country State City
  • Step 6: Create Blade File For Show Dependent Country State City in Dropdown
  • Step 7: Run Development Server

https://www.tutsmake.com/ajax-country-state-city-dropdown-in-laravel/

#how to create dynamic dropdown list using laravel dynamic select box in laravel #laravel-country state city package #laravel country state city drop down #dynamic dropdown country city state list in laravel using ajax #country state city dropdown list using ajax in php laravel #country state city dropdown list using ajax in laravel demo

Laravel 8 Database Seeder Example

Today we will see Laravel 8 Database Seeder Example, as we all know laravel framework provide many functionalities to user to reduce developer’s time for developing website, here we will see How to create database seeder in Laravel 8.

Many times you have requirement to add some default records or entry to login or add form details etc. there are no problem to add manual data in database one or two times but it is very challenging task to add data manually each and every time.

Laravel 8 Database Seeder Example

https://websolutionstuff.com/post/laravel-8-database-seeder-example


Read Also : Read Also : Laravel 8 CRUD Operation Example

https://websolutionstuff.com/post/laravel-8-crud-operation-example


Read Also : Read Also : Create Dummy Data Using Laravel Tinker

https://websolutionstuff.com/post/create-dummy-data-using-laravel-tinker

#laravel 8 database seeder example #laravel #database #seeder #database seeders in laravel 8 #laravel 8 seeder example

How to Send E-mail Using Queue in Laravel 7/8

Today I will show you How to Send E-mail Using Queue in Laravel 7/8, many time we can see some process take more time to load like payment gateway, email send, etc. Whenever you are sending email for verification then it load time to send mail because it is services. If you don’t want to wait to user for send email or other process on loading server side process then you can use queue.

Read More : How to Send E-mail Using Queue in Laravel 7/8

https://websolutionstuff.com/post/how-to-send-e-mail-using-queue-in-laravel-7-8


Read Also : Send Mail Example In Laravel 8

https://websolutionstuff.com/post/send-mail-example-in-laravel-8

#how to send e-mail using queue in laravel 7/8 #email #laravel #send mail using queue in laravel 7 #laravel 7/8 send mail using queue #laravel 7/8 mail queue example

How To Create Zip File Using Ziparchive in Laravel

In this tutorial i will show you how to create zip file using zipArchive in laravel. Some times client’s have requirements to have functionalities like create zip file for documentation or images and download it.

So, at that time we can find many laravel packages to perform this task. But here, i am show you to how to create zip file in laravel using zipArchive without any package. Laravel provide ZipArchive class for create zip file in laravel,So i will use ZipArchive in laravel.

How To Create Zip File Using Ziparchive in Laravel

https://websolutionstuff.com/post/how-to-create-zip-file-using-ziparchive-in-laravel

#laravel #ziparchive #how to create zip file using ziparchive in laravel #ziparchive in laravel #make zip in laravel #ziparchive laravel example