In this third part of creating WordPress-Like Blog using Laravel 5.6 and AdminLTE 3, we will :
- Create Post model and posts table
- Prepare some dummy data using database seeder
Before we proceed, we need to make sure the database information inside .env file has been properly set according to your database credentials :
1 2 3 4 5 6 |
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=laravel_adminlte DB_USERNAME=root DB_PASSWORD=root |
1. Create Post Model and posts table
Open terminal, and type:
1 |
php artisan make:model Post -m |
The command will automatically create Post model and table posts through -m migration command.
Open database/migration folder, find the newly created migration file, then let’s fill the migration file that we had just created as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreatePostsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('posts', function (Blueprint $table) { $table->increments('id'); $table->integer('author_id')->unsigned(); $table->foreign('author_id')->references('id')->on('users')->onDelete('restrict'); $table->string('title'); $table->string('slug')->unique(); $table->text('excerpt'); $table->text('body'); $table->string('image')->nullable(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('posts'); } } |
The author_id column is made to store the user id information, who wrote the post.
Run the migration by typing :
1 |
php artisan migrate |
Open your database administrator (PhpMyAdmin or Sequel Pro or Navicat), the posts table will appear.
2. Prepare Dummy Data using Database Seeder
We can manually insert data through database administrator like phpmyadmin, sequel pro, or navicat. However, we will be using database seed to fill our posts table. Let’s start by creating PostsTableSeeder and UsersTableSeeder.
1 2 |
php artisan make:seed PostsTableSeeder php artisan make:seed UsersTableSeeder |
UsersTableSeeder.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
<?php use Illuminate\Database\Seeder; class UsersTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { //reset table DB::statement('SET FOREIGN_KEY_CHECKS=0'); DB::table('users')->truncate(); DB::table('users')->insert([ [ 'name' => "Super Administrator", 'password' => bcrypt('123secret') ], [ 'name' => "Administrator", 'password' => bcrypt('123secret') ], [ 'name' => "Client User", 'password' => bcrypt('123secret') ], ]); } } |
We have created three users from UsersTableSeeder.
PostsTableSeeder.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
<?php use Illuminate\Database\Seeder; use Faker\Factory; use Carbon\Carbon; class PostsTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { //reset posts table DB::table('posts')->truncate(); //generate 10 dummy posts $image = "http://placehold.it/750x300"; $posts = []; $faker = Factory::create(); $date = Carbon::create(2018, 7, 10, 11); for($i=1; $i<=10; $i++){ $date->addDays(1); $publishedDate = clone($date); $createdDate = clone($date); $posts[] = [ 'author_id' => rand(1,3), 'title' => $faker->sentence(rand(8,12)), 'excerpt' => $faker->text(rand(250,300)), 'body' => $faker->paragraphs(rand(10,15), true), 'slug' => $faker->slug(), 'image' => rand(0,1) == 1 ? $image : null, 'created_at' => $createdDate, 'updated_at' => $createdDate, ]; } DB::table('posts')->insert($posts); } } |
We use Faker\Factory library to create dummy data. Faker create mock up strings such as sentences, words, even paragraphs.
Modify DatabaseSeeder.php, take note that UsersTableSeeder::class should be placed before PostsTableSeeder.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<?php use Illuminate\Database\Seeder; class DatabaseSeeder extends Seeder { /** * Seed the application's database. * * @return void */ public function run() { $this->call(UsersTableSeeder::class); $this->call(PostsTableSeeder::class); } } |
Next step is to generate the seeder. Open your terminal and type:
1 |
php artisan db:seed |
This command will generate the seeder. Now check your users and posts table. They have filled with dummy data successfully.
when i run:
php artisan migrate
i get this error:
Illuminate\Database\QueryException : SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table
posts
add constraintposts_author_id_foreign
foreign key (author_id
) referencesusers
(id
) on delete restrict)at /var/www/html/becauseican/vendor/laravel/framework/src/Illuminate/Database/Connection.php:664
660| // If an exception occurs when attempting to run a query, we’ll format the error
661| // message to include the bindings with SQL, which will make this exception a
662| // lot more helpful to the developer instead of just the database’s errors.
663| catch (Exception $e) {
> 664| throw new QueryException(
665| $query, $this->prepareBindings($bindings), $e
666| );
667| }
668|
Exception trace:
1 PDOException::(“SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint”)
/var/www/html/becauseican/vendor/laravel/framework/src/Illuminate/Database/Connection.php:458
2 PDOStatement::execute()
/var/www/html/becauseican/vendor/laravel/framework/src/Illuminate/Database/Connection.php:458
can you please help?
Hi,
change $table->integer(‘author_id’)->unsigned();
to $table->bigInteger(‘author_id’)->unsigned();
change $table->integer(‘author_id’)->unsigned();
to $table->bigInteger(‘author_id’)->unsigned();