Seeding mock listings
Now that we have a database table for our listings, let's seed it with the mock data. To do so we're going to have to do the following:
- Load the
database/data.json
file - Parse the file
- Insert the data into the listings table
Creating a seeder
Laravel includes a seeder class that we can extend called Seeder
. Use this Artisan command to implement it:
$ php artisan make:seeder ListingsTableSeeder
When we run the seeder, any code in the run
method is executed.
database/ListingsTableSeeder.php
:
<?php use Illuminate\Database\Seeder; class ListingsTableSeeder extends Seeder { public function run() { // } }
Loading the mock data
Laravel provides a File
facade that allows us to open files from disk as simply as File::get($path)
. To get the full path to our mock data file we can use the base_path()
helper function, which returns the path to the root of our application directory as a string.
It's then trivial to convert this JSON file to a PHP array using the built-in json_decode...