Seeding test data in Laravel, a full guide

https://accreditly.io/storage/blogs/125/seeding-test-data-in-laravel-a-full-guide-1000.webp

3 min read

Published on 1st September 2023

Testing is an integral part of software development, and Laravel provides a robust framework for setting up tests. However, sometimes you need dummy data to test your application efficiently. In Laravel, this is done using seeders and the Faker library. This guide will walk you through creating and seeding test data in a Laravel application.

1. Introduction to Seeding

Seeders in Laravel provide a convenient way to populate your database with sample data. This is particularly useful during the development phase when you want to test your application with real-ish data.

2. Setting Up

Before you can use seeders, make sure you’ve set up a database and configured your .env file with the correct database connection details.

3. Creating a Seeder

To create a seeder, use the Artisan command-line tool:

php artisan make:seeder UsersTableSeeder

This will generate a new seeder class in the database/seeders directory.

4. Using Faker

Laravel uses the Faker library for generating random data. This library provides a plethora of methods to create data of different types.

You can even create your own formatters in Faker if you have specific format of data you need.

To use Faker in your seeder:

use Faker\Factory as Faker;

public function run()
{
    $faker = Faker::create();

    foreach (range(1, 10) as $index) {
        DB::table('users')->insert([
            'name' => $faker->name,
            'email' => $faker->email,
            'password' => bcrypt('secret'),
        ]);
    }
}

5. Model Factories

While seeders are powerful, Laravel recommends using model factories for generating large sets of test data.

Step 1: Create a factory.

php artisan make:factory UserFactory

This will create a new factory in the database/factories directory.

Step 2: Define the model’s default state.

use App\Models\User;

$factory->define(User::class, function (Faker $faker) {
    return [
        'name' => $faker->name,
        'email' => $faker->unique()->safeEmail,
        'password' => bcrypt('password'),
    ];
});

Step 3: Use the factory in your seeder.

public function run()
{
    factory(App\Models\User::class, 50)->create();
}

This will create 50 users with random names, emails, and passwords.

6. Relationships and Test Data

Often, you’ll want to create test data that has relationships. For instance, a user might have many posts.

First, you’d define a relationship in the User model:

public function posts()
{
    return $this->hasMany('App\Models\Post');
}

Then, in the Post factory:

$factory->define(App\Models\Post::class, function (Faker $faker) {
    return [
        'user_id' => function () {
            return factory(App\Models\User::class)->create()->id;
        },
        'title' => $faker->sentence,
        'body' => $faker->paragraph,
    ];
});

7. Running Seeders

Once your seeders are set up, you can run them using:

php artisan db:seed --class=UsersTableSeeder

Or to run all seeders:

php artisan db:seed

8. Resetting and Reseeding

If you want to rollback all your migrations, run them again and then run the seeders, you can use:

php artisan migrate:refresh --seed

Seeding test data in Laravel can greatly improve the development and testing process. Using the combination of seeders, the Faker library, and model factories, you can generate realistic data sets to effectively test your application’s functionality.

Remember, while this data is great for development and testing, always ensure your production database is secured and not populated with test data.

Laravel News Links

Making Order from Chaos

https://theawesomer.com/photos/2024/06/order_from_chaos_t.jpgIf you dump a bunch of dice into a jar, they’ll just land in random positions. But if you jiggle the jar while spinning it, they will eventually work their way into orderly layers, filling in all the gaps. The Action Lab’s physics lesson explains the entropic forces at work that encourage objects to organize […]The Awesomer

ChatGPT for macOS no longer requires a subscription

The macOS ChatGPT desktop app is now available to everyone. That is, provided you’re running an Apple Silicon Mac (sorry, Intel users) and your computer is on macOS Sonoma or higher. OpenAI rolled out the app gradually, starting with Plus subscribers last month.

ChatGPT now has an official macOS client before it has a Windows one. (In case you haven’t heard, Microsoft is its most crucial partner.) Of course, Windows 11 has the OpenAI-powered Microsoft CoPilot baked into its OS, which likely explains the omission. OpenAI and Apple are also teaming up on Apple Intelligence, which arrives later this year (unless you’re in Europe).

The Mac app includes a keyboard shortcut (option-space by default, but it’s customizable) for typing chatbot queries from anywhere in macOS. Otherwise, the app mirrors the ChatGPT website’s appearance and functionality (including custom GPTs), except in native app form. You can also upload files, photos and screenshots.

You can download and install ChatGPT for macOS from OpenAI.

This article originally appeared on Engadget at https://www.engadget.com/chatgpt-for-macos-no-longer-requires-a-subscription-204959264.html?src=rssEngadget

Pastor Informs Worship Leader It’s Inappropriate To Bring Tuba And Lead Congregation In VeggieTales Theme Song

https://media.babylonbee.com/articles/6679ca34076a36679ca34076a4.jpg

CLEVELAND, OH — Congregants at St. James Church report that Pastor Paul Mendoza set an inspiring example of Christian charity and forbearance by calmly explaining to worship leader Jason Green that bringing a tuba and playing the VeggieTales theme song during the service is inappropriate.

According to eyewitnesses, Mendoza spent 20 minutes explaining the concept of proper reverence in corporate worship to the disappointed worship leader without once raising his voice or rolling his eyes.

"I get what you’re going for, but I just don’t think it’s appropriate," Mendoza kindly explained to Green, who was sadly holding his tuba. "The point of worship is that the congregation reverently and gratefully sings praises to the Lord who made heaven and earth, not that they sing about anthropomorphic vegetables. And it is a little bit sanctimonious to lead into the sermon with the phrase ‘do we have a show for you!’"

Mendoza went on to point out that the song says "half an hour", and he couldn’t guarantee his sermon wouldn’t go on for well over that.

Sources say that Pastor Mendoza also requested that Green refrain from breaking into "The Cheeseburger Song" and "Barbara Manatee", even if he thinks that they would fit really nicely with the sermon topic.

At publishing time, Green had reluctantly decided to cut "The Water Buffalo Song" from the plan for next Sunday’s service after learning that not everybody has a water buffalo.


Bob Boeing, the founder of Boeing, explains how the number 1 priority for the airline manufacturer is diversity.

Subscribe to our YouTube channel for more uplifting DEI videos!

Babylon Bee

Researchers Say They Are Now Over 60% Confident Ohio Exists

https://media.babylonbee.com/articles/6679c67594cbf6679c67594cc0.jpg

U.S. — Researchers reported this week that they are now over 60% confident Ohio exists.

"We’ve looked into it, and we’re now pretty sure," said Dr. Frank Paulson, the lead researcher of the federally funded study. "I mean, as sure as you can be about these kinds of things." Scientists say they have found "fairly convincing" evidence such as highway signs in definitely real states like Indiana, Michigan, and Pennsylvania that mention Ohio, something called Cincinatti chili, and several semi-professional sports teams like the Bengals and Browns.

Experts had begun looking into the existence of the once-mythical state after thinking about it for a while and realizing that no one knew what was under Michigan and above Kentucky.

"So, yeah, Ohio. It’s a thing, apparently," said Paulson.

Scientists aren’t sure what to do with the information, pointing out that while this is a groundbreaking discovery, "it’s still just, you know, Ohio."


Bob Boeing, the founder of Boeing, explains how the number 1 priority for the airline manufacturer is diversity.

Subscribe to our YouTube channel for more uplifting DEI videos!

Babylon Bee

New difficulty mod in Stardew Valley will purge your saves if you use a guide

A great number of us have played games in extra-difficult modes (or in the case of Kingdom Hearts, Proud Mode) to challenge ourselves. Now, a Stardew Valley player has created a “hardcore” option for the otherwise chill game, one that will delete the save files of any player who uses a guide while playing the game on PC.

According to GamesRadar, software engineer Sylvie Nightshade created the high difficulty mod on June 21 after reading an article published the day before on the satirical website Hard Drive, the gaming version of The Onion. The article in question joked about a “hardcore mode” in Stardew Valley that will delete players’ hard grown farms if they dare read the wiki at any point during gameplay. That same day, Nightshade quote-tweeted the article on X with the link to the mod in GitHub announcing that she turned the joke into reality.

The mod works by scanning the title of every window or tab that is open while Stardew Valley is running. If any window title includes “Stardew Valley Wiki” in the title, it erases everything the player has worked hard to achieve, forcing them to start from square one without using the guide. Nightshade even updated the mod so that it not only deletes the player’s save file but also closes the browser window the wiki was found in “just to add insult to injury.”

Hardcore mode being programmed into Stardew Valley is another case of life imitating art after Hello Kitty Island Adventure launched on Apple Arcade 17 years after it was mentioned as a joke in the South Park episode “Make Love, Not Warcraft.” Here’s a tip: If you play Stardew Valley on hardcore mode on your computer but use the guide on your phone, you should be safe.

This article originally appeared on Engadget at https://www.engadget.com/new-difficulty-mod-in-stardew-valley-will-purge-your-saves-if-you-use-a-guide-175521779.html?src=rssEngadget

Trump Preps For Debate Against Biden By Going to Nursing Home And Arguing With Dementia Patients

https://media.babylonbee.com/articles/6679adcb2c0216679adcb2c022.jpg

WEST PALM BEACH, FL — The Trump campaign announced Monday that the former president had begun preparing for his upcoming debate with Joe Biden by visiting nursing homes and arguing with dementia patients.

"George, you’re wrong about Lime JELL-O. Nobody likes it," Trump said as he argued with a 94-year-old man dementia patient who claims to be constantly observed by Russian spies. "It doesn’t taste good! Everyone’s telling me all the time how much they hate it and you’re going to say they should serve it every day? On DAY ONE I will ban Lime JELL-O."

Elderly onlookers applauded as Trump slammed the dementia patient after suddenly picking a fight with him while he ate his dessert.

"It’s like he’s saying what we’re all thinking," said Constance Woodrow, a 78-year-old Alzheimer’s patient.

In another instance, Trump yelled at a WWII veteran until he started crying.

"Greatest generation? More like lamest generation," Trump quipped, invoking laughs from orderlies. "You complain about loud music when people — good people — are trying to listen to jazz. You make me sick, to tell you the truth."

"But thank you for your service."

In this, and many such cases, a crowd of old folks erupted in cheers for Trump as he blasted one dementia patient after another.

This new strategy for debate prep is a distinct departure from previous campaign years when he spent time studying government policy and took part in mock debates against former New Jersey Governor Chris Christie.

"I spent all my time arguing against a fat man about bridges or something," Trump said, reflecting on past debate missteps. "It didn’t prepare me at all. Biden is thin and he hates bridges!"

Sources close to the Biden campaign confirm the president is concerned about this new development leading up to Thursday’s debate.

"Oh no, my ice cream," Biden reportedly said, concern all over his face as his wife led him away.

At publishing time, sources had confirmed that if Trump fails to win the presidency he will be welcome at Shady Oaks Assisted Living.


Bob Boeing, the founder of Boeing, explains how the number 1 priority for the airline manufacturer is diversity.

Subscribe to our YouTube channel for more uplifting DEI videos!

Babylon Bee

Save up to $650 on Apple’s latest 14-inch MacBook Pro with M3 Pro, M3 Max chip

https://photos5.appleinsider.com/gallery/60137-123457-macbook-pro-m3-pro-m3-max-deals-xl.jpg

Save on Apple’s latest 14-inch MacBook Pro.


Steeper discounts are in effect on Apple’s current 14-inch MacBook Pro, with every M3 Pro and M3 Max configuration up to $650 off. Plus, grab a bonus discount on three years of AppleCare with coupon.

We’re tracking fresh price drops on Apple’s 14-inch MacBook Pro, with savings of up to $650 off thanks to instant rebates stacked with promo code APINSIDER at Apple Authorized Reseller Adorama.

If you’re looking for the lowest price period, the cheaper M3 14-inch MacBook Pro is also eligible for a coupon discount on every configuration. The M3 version has fewer ports and comes in Space Gray vs the Space Black option found in the M3 Pro / M3 Max line. You can find a rundown of the chip differences in our M3, M3 Pro & M3 Max chip comparison.

Those looking to protect their purchase can also save $50 on three years of AppleCare with the same APINSIDER coupon, regardless of which 14-inch model is selected.

How to activate the APINSIDER coupon code at Adorama

If you need help redeeming the APINSIDER discount, you can find step-by-step instructions below:

  1. Add the MacBook Pro to your Adorama shopping cart.
  2. Proceed to checkout. When you get to step 4 (Payment), look for a link with a gift icon that says: "Do you have a gift card or promo code?"
  3. Click that link to bring up the promo code field and enter APINSIDER. Here’s what the process looks like:

Enter promo code APINSIDER during Step 4 of checkout.

About Adorama

Adorama is celebrating 50 years in business, having started as a camera shop in New York City in 1974. Since then, the company has grown to sell Apple computers, high-end speakers, drones and much more. In addition to being an Apple Authorized Reseller, Adorama is also authorized to sell products from Canon, Nikon, Sony and more.

Adorama’s physical store in New York City features Apple hardware.

Adorama also offers AppleInsider readers exclusive pricing on nearly every Mac computer available, as well as special discounts on the 2024 iPad Pro and iPad Air models. You can access hundreds of deals in our Apple Price Guide and in our roundup of the best MacBook Pro deals.

AppleInsider News