Faker is a library that generates fake data for us. Faker helps us populate the database which helps to speed the development process. It makes us easy while writing test cases, load/stress testing, working with APIs and databases.
In this article, we will learn about seeding our database but more importantly seeding images. Faker provides different methods to seed our database. In Laravel, we can seed using factories. An example factories can be found inside /database/factories/
directory. Some of the basic examples of seeding database are as follow.
<?php
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
/**
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\User>
*/
class UserFactory extends Factory
{
/**
* Define the model's default state.
*
* @return array
*/
public function definition()
{
return [
'name' => $this->faker->name(),
'email' => $this->faker->unique()->safeEmail(),
'email_verified_at' => now(),
'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
'remember_token' => Str::random(10),
];
}
/**
* Indicate that the model's email address should be unverified.
*
* @return \Illuminate\Database\Eloquent\Factories\Factory
*/
public function unverified()
{
return $this->state(function (array $attributes) {
return [
'email_verified_at' => null,
];
});
}
}
Faker library provides different methods. Below is a list of all the formatters.
- Numbers and Strings
- Text and Paragraphs
- Date and Time
- Internet
- User Agent
- Payment
- Color
- File
- Image
- UUID
- Barcode
- MiscellaneousBiased
- HTML Lorem
- Version
Now, we will look how we can seeds images in our database. For this, we need to call the image()
method in our faker instance. A basic example looks like below.
..........
public function definition()
{
return [
'avatar' => $this->faker->image(storage_path('images'), 300, 300)
];
}
In this example, we called image()
method passing directory
, width
and height
as first second and third parameters. After we hit the seed command php artisan db:seed
, it will generate a list of images inside the storage/images folder. Then, those images name will be stored in the respective tables. However, we need to create a symlink for the storage folder using command.
php artisan storage:link
If we check at the source code of this method, we can see that it accepts other parameters as well.
image($dir = null, $width = 640, $height = 480, $category = null, $fullPath = true, $randomize = true, $word = null, $gray = false)
If you get the error message as Cannot write to directory "/var/www/laravel9/storage/images"
while running the seed command, you need to give read write permission to the storage folder.
chmod -R 755 storage
Similarly, we can also use other methods such as imageUrl which generates a random image URL from placeholder.com. Moreover, we can also use seed files using file()
method.