Dev Notes

Software Development Resources by David Egan.

Set Up & Seed Laravel Database


Laravel, MariaDB, MySQL
David Egan

These instructions are for local development of Laravel on Ubuntu 16.04 Xenial Xerus (Desktop). The instrauctions have been tested on 10.1.16-MariaDB, but they should also work for MySQL.

Create Database

Create a Database with a unique user:

mysql -u root -p -e "create database database_name; GRANT ALL PRIVILEGES ON database_name.* TO user_name@localhost IDENTIFIED BY 'urehfh577hg5hrpefh7'"

Connect Laravel

Enter the Databse connection details in .env:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=database_name
DB_USERNAME=user_name
DB_PASSWORD=urehfh577hg5hrpefh7

Test the Database

Laravel comes with a couple of migrations defined out of the box.

To check that Laravel is properly connected to the new database:

# Open a mysql prompt, working on the new DB:
mysql -u root -p database_name
# Enter show tables:
SHOW TABLES;
# Returns Empty set (0.00 sec)

Open a new terminal and run the pending Laravel migrations:

php artisan migrate

This will run the default migrations (under Laravel 5.3, a “users” table and a “password_resets” table will be created, as well as a “migrations” table).

You can also seed the database. Create a seeder class:

php artisan make:seeder UsersTableSeeder

This will create database/seeds/UsersTableSeeder.php, which will be stubbed out with an empty run() method.

This method can be used to insert records into the database. Laravel includes the handy Faker factory class, which allows dummy data to be created.

To determine which fields to seed, check the table:

# At the mysql prompt:
SHOW COLUMNS FROM users;

Next, amend the run() method of the seeder class that you’ve just created:

<?php
public function run()
    {
      $faker = Faker\Factory::create();

        for( $i = 0; $i < 25; $i++ ) {

          DB::table('users')->insert([
            'password' => bcrypt('secret'),
            'name' => $faker->name,
            'email' => $faker->email

          ]);
        }
    }

Now, when you run:

php artisan db:seed --class=UsersTableSeeder

…the seeder will create 25 dummy users complete with realistic data.

Note: running php artisan db:seed will only run the default DatabaseSeeder class - which will be empty. This is a bit different to the php artisan migrate command, which runs all migrations under the database/migrations directory.

To check the seeder results, run the following command from the mysql prompt:

SELECT * FROM users;

Note that Laravel has a much better way of interacting with your database on the fly - Artisan tinker:

# Get the tinker prompt:
php artisan tinker

# Show all users:
App\User::all()->toArray();

comments powered by Disqus