@ajagabos007 I like method 2 (not sure it is the best or not).
Oct 14, 2022
8
Level 1
Seeder class Code review, refactory and best method to use
Please which is the best between method 1 (use Illuminate\Database\Eloquent\Factories\Sequence) and method 2 ( array and foreach ) to write my seeder class having known values?
<?php
namespace Database\Seeders;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use App\Models\Category;
use Cviebrock\EloquentSluggable\Services\SlugService;
use Illuminate\Database\Eloquent\Factories\Sequence;
class CategorySeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
// METHOD 1 : USING SEQUENCE
$categories = Category::factory()->count(9)->state(new sequence(
[
'name' => 'Home and Office',
'slug' => SlugService::createSlug(Category::class, 'slug','Home and Office'),
],
[
'name' => 'Phone and Tablets',
'slug' => SlugService::createSlug(Category::class, 'slug','Phone and Tablets'),
],
[
'name' => 'Computing',
'slug' => SlugService::createSlug(Category::class, 'slug','Computing'),
],
[
'name' => 'Electronics',
'slug' => SlugService::createSlug(Category::class, 'slug','Electronics'),
],
[
'name' => 'Fashion',
'slug' => SlugService::createSlug(Category::class, 'slug','Fashion'),
],
[
'name' => 'Baby Products',
'slug' => SlugService::createSlug(Category::class, 'slug','Baby Products'),
],
[
'name' => 'Gaming',
'slug' => SlugService::createSlug(Category::class, 'slug','Gaming'),
],
[
'name' => 'Sporting Goods',
'slug' => SlugService::createSlug(Category::class, 'slug','Sporting Goods'),
],
[
'name' => 'Automobile',
'slug' => SlugService::createSlug(Category::class, 'slug','Automobile'),
],
));
// METHOD 2: USING ARRAY AND FOREACH
/**
* @var array $categories
*/
$categories =[
'Home and Office',
'Phone and Tablets',
'Computing',
'Electronics',
'Fashion',
'Baby Products',
'Gaming',
'Sporting Goods',
'Automobile',
];
foreach($categories as $key=>$value){
$category = new Category();
$category->name = $value;
$category->slug = SlugService::createSlug(Category::class, 'slug',$value);
$category->save();
}
}
}
Level 104
@ajagabos007 it’s completely unnecessary IMHO; a seeder doesn’t have to use a Factory. You have a simple list of strings representing the names of Caregory instances; slug generation can be handled on the Model
$categories =[
'Home and Office',
'Phone and Tablets',
'Computing',
'Electronics',
'Fashion',
'Baby Products',
'Gaming',
'Sporting Goods',
'Automobile',
];
foreach($categories as $category){
Category::create([‘name’ =>$category]) ;
}
1 like
Please or to participate in this conversation.