Category: Projects
Topic: Mini Ecommerce
Created: 3 years ago
// artisan command for migration, factory and seeder file
php artisan make:model Product -mfs
// migration file
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained();
$table->string('name');
$table->string('slug');
$table->text('description');
$table->float('cost');
$table->tinyInteger('status');
$table->integer('sequence');
$table->timestamps();
});
}
// ProductFactory.php file
namespace Database\Factories;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
class ProductFactory extends Factory
{
/**
* Define the model's default state.
*
* @return array
*/
private static $order = 1;
public function definition()
{
$userIds = User::pluck('id');
$name = $this->faker->text(50);
return [
'user_id' => $userIds->random(),
'name' => $name,
'slug' => Str::slug($name),
'cost' => $this->faker->randomFloat(2, 10, 40),
'description' => $this->faker->text(500),
'status' => rand(0,1),
'sequence' => self::$order++
];
}
}
// ProductSeeder.php file
namespace Database\Seeders;
use App\Models\Product;
use Illuminate\Database\Seeder;
class ProductSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
//
Product::factory(30)->create();
}
}