如何利用faker Laravel 6解决种子上的故障名称图像

如何利用faker Laravel 6解决种子上的故障名称图像,laravel,Laravel,我创建了一个表,这个表名为book 我创建了一个种子机来在表中添加数据,这个表有这样一个查询 public function run() { $books = []; $faker = Faker\Factory::create(); $image_categories = ['abstract', 'animals', 'business', 'cats', 'city', 'food', 'nature', 'technics', 'transport

我创建了一个表,这个表名为book

我创建了一个种子机来在表中添加数据,这个表有这样一个查询

public function run()
{
    $books = [];
    $faker = Faker\Factory::create();
    $image_categories = ['abstract', 'animals', 'business', 'cats',
    'city', 'food',
    'nature', 'technics', 'transport'];
    for($i=0;$i<25;$i++){
      $title = $faker->sentence(mt_rand(3, 6));
      $title = str_replace('.', '', $title);
      $slug = str_replace(' ', '-', strtolower($title));
      $category = $image_categories[mt_rand(0, 8)];
      $cover_path = 'C:\xampp\htdocs\larashop-api\public\images\books';
      $cover_fullpath = $faker->image( $cover_path, 300, 500,
      $category, true, true, $category);
      $cover = str_replace($cover_path . '/' , '', $cover_fullpath);
      $books[$i] = [
    'title' => $title,
    'slug' => $slug,
    'description' => $faker->text(255),
    'author' => $faker->name,
    'publisher' => $faker->company,
    'cover' => $cover,
    'price' => mt_rand(1, 10) * 50000,
    'weight' => 0.5,
    'status' => 'PUBLISH',
    'created_at' => Carbon\Carbon::now(),
    ];
    }
    DB::table('books')->insert($books);
        }
公共函数运行()
{
$books=[];
$faker=faker\Factory::create();
$image_categories=[“抽象”、“动物”、“商业”、“猫”,
"城市","食物",,
“自然”、“工艺”、“运输”];
对于($i=0;$i强度(mt_rand(3,6));
$title=str_替换('.','.$title);
$slug=str_replace(“”,“-”,strtolower($title));
$category=$image_categories[mt_rand(0,8)];
$cover_path='C:\xampp\htdocs\larashop api\public\images\books';
$cover\u fullpath=$faker->image($cover\u path,300500,
$category,true,true,$category);
$cover=str_replace($cover_path.'/','',$cover_fullpath);
$books[$i]=[
“title”=>$title,
“slug”=>$slug,
'description'=>$faker->text(255),
'author'=>$faker->name,
“出版商”=>$faker->company,
“封面”=>$cover,
“价格”=>百万兰特(1,10)*50000,
“重量”=>0.5,
“状态”=>“发布”,
'在'=>Carbon\Carbon::now()处创建,',
];
}
DB::table('books')->insert($books);
}
这些数据(如标题、slug和所有数据)成功输入数据库,但这覆盖了,我在public/images/books中创建了一个文件夹来保存图像。它的工作,但该图像名称无效

例如,在我的文件夹中,我的图像名是:qwertyuiop.jpg

但在数据库中,名称是:C:\xampp\htdocs\larashop api\public\images\books\qwertyuiop.jpg


我认为是它的错误,将给出一个错误。我如何解决此问题>

您可以通过提取图像名从
$cover\u fullpath
获取图像名:

$cover_path = 'C:\xampp\htdocs\larashop-api\public\images\books';
$cover_fullpath = $faker->image( $cover_path, 300, 500,$category, true, true, $category);
// after above code add this line so in cover_path you will have only image name
$cover_path = explode("\\",$cover_fullpath)[0];

只需将封面路径设置为:$cover_path='images\books';因此您的图像路径将是:images\books\qwertyuiop.jpg,您可以直接访问它Url::to(),我使用$cover_path='images\books';添加图像路径,但出现错误:无法写入目录“images\books”我只想保存图像名。不使用DirectoryOK,等等,我会试试这个,