Files
eatvio-infra/database/seeders/RecipeSeeder.php

73 lines
2.9 KiB
PHP

<?php
namespace Database\Seeders;
use Illuminate\Support\Facades\Storage;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use App\Models\Recipe;
use App\Models\RecipeComment;
use App\Models\RecipeAuthor;
use App\Models\User;
use Faker\Factory as FakerFactory;
use DB;
class RecipeSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$faker = FakerFactory::create();
$images = [];
for ($i = 0; $i < 10; $i++) {
$recipe = new Recipe();
$recipe->image = $this->downloadRandomImage();
$recipe->state = 'active';
$recipe->type = $faker->randomElement(['first_meals', 'second_meals', 'salads', 'snacks', 'drinks', 'other']);
$recipe->title = $faker->sentence(5);
$recipe->video_url = $faker->url;
$recipe->cooking_time = $faker->randomElement([10,20,30,60,120,14400]);
$recipe->description = $faker->text(200);
$recipe->steps = [
['image' => $this->downloadRandomImage(), 'description' => $faker->text(100)],
['image' => $this->downloadRandomImage(), 'description' => $faker->text(100)],
['image' => $this->downloadRandomImage(), 'description' => $faker->text(100)]
];
$recipe->ingredients = [
['name' => $faker->word, 'portion' => $faker->numberBetween(1, 20), 'unit' => $faker->randomElement(['teespoon', 'tablespoon', 'ml', 'pcs', 'clove', 'to_taste'])],
['name' => $faker->word, 'portion' => $faker->numberBetween(1, 20), 'unit' => $faker->randomElement(['teespoon', 'tablespoon', 'ml', 'pcs', 'clove', 'to_taste'])],
['name' => $faker->word, 'portion' => $faker->numberBetween(1, 20), 'unit' => $faker->randomElement(['teespoon', 'tablespoon', 'ml', 'pcs', 'clove', 'to_taste'])],
];
$recipe->save();
for ($j = 0; $j < 10; $j++) {
$comment = new RecipeComment();
$comment->user_id = User::inRandomOrder()->first()->id;
$comment->recipe_id = $recipe->id;
$comment->grade = $faker->randomElement([1,2,3,4,5]);
$comment->body = $faker->text(100);
$comment->save();
}
User::inRandomOrder()->first()->author_of_recipe()->attach($recipe->id);
}
}
public function downloadRandomImage(): string
{
$faker = FakerFactory::create();
$url = $faker->imageUrl(640, 480, 'food', true);
$contents = file_get_contents($url);
$dir_path = storage_path('app/public/recipe');
$path = 'recipe/' . uniqid() . '.jpg';
if (!file_exists( $dir_path)) {
mkdir( $dir_path, 0777, true);
}
file_put_contents(storage_path('app/public/' . $path), $contents);
return $path;
}
}