laravel - foreach重复多次

时间:2018-06-08 16:20:58

标签: laravel for-loop foreach

我有两个型号:User& Book。我想为每个具有特定QR码的用户创建一本书

$users = User::get();
$date = ... ;
$finalCount = 0;
$code = 150;
$userCount = count($users);
foreach ($users as $user) {
    $book = new Book();
    $book->unique_id = uniqid('', true);
    $book->user_id = $user->unique_id;
    $book->code = "PP-" . strval(mt_rand(100, 999)) . strval($code);
    $book->create_date = $date;
    $book->status = 'active';
    $book->save();

    $QRCode = new BaconQrCodeGenerator;
    $file = public_path('/images/book/' . $book->code . '.png');
    $QRCode->encoding('UTF-8')
        ->format('png')
        ->merge('/public/image/logo.png', .15)
        ->size(1000)
        ->generate($book->unique_id, $file);
    if (File::exists($file))
        $finalCount++;
    $code++;
    if ($finalCount == $userCount)
        break;
}

调用此函数后,每个用户都有20本书。我使用if语句来打破循环(if ($finalCount == $userCount)),但它不起作用 我无法理解这里发生了什么,我也没有任何错误日志

1 个答案:

答案 0 :(得分:0)

而不是

$file = public_path('/images/book/' . $book->code . '.png'); 

尝试

$file = public_path().'/images/book/' . $book->code . '.png';