gpt4 book ai didi

php - For 循环在 Laravel Controller 类中不起作用

转载 作者:行者123 更新时间:2023-12-05 01:46:17 29 4
gpt4 key购买 nike

在我的 Laravel 项目中,我有一个 BusController.php 文件,我需要在其中运行 for() 循环。但是,循环不起作用。我也尝试了一个用于循环的 Blade ,但遇到了同样的问题。

BusController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;
use App\Bus;
use App\Bus_type;
use App\Company;
use App\Http\Requests;

class BusController extends Controller
{
public function index()
{
$buses = Bus::all();
$bus_types = Bus_type::all();
$companies = Company::all();

return view('admin.adding_bus', compact('buses', 'bus_types', 'companies'));
}

public function store(Request $request)
{
$bus = new Bus;
$bus->company_name = $request->company_name;
$bus->bus_type = $request->bus_type;
$bus->bus_number = $request->bus_number;
$bus->no_of_rows = $request->no_of_rows;
$bus->no_of_columns = $request->no_of_columns;
$seats = "";

for ($i = 1; $i <= ($request->no_of_rows * $request->no_of_columns); $i++) {
$seats = $seats . "b";
}
$bus->seats = $seats;

$bus->save();
$buses = Bus::all();
$bus_types = Bus_type::all();
$companies = Company::all();

return view('admin.adding_bus', compact('buses', 'bus_types', 'companies'));
}
}

最佳答案

确保您已经验证了从Request 收到的数据。因为如果你不这样做,循环就会失败,因为 loop condition 总是 false。为了测试它,我会这样做:

$seats = "";
$num_cols = 2;
$num_rows = ''; // assume you don't validate the request, so this can receive empty string too
// $num_rows = 0; // will output the same as above
for($i = 1;$i<=($num_cols * $num_rows);$i++)
{
$seats = $seats."b";
}
var_dump($seats);

输出:

string(0) ""

这是工作的一个:

$seats = "";
$num_cols = 2;
$num_rows = 20; // correctly validated as integer and must be more than 0 because you're doing multiplication here in the following loop
for($i = 1;$i<=($num_cols * $num_rows);$i++)
{
$seats = $seats."b";
}
var_dump($seats);

输出:

string(40) "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"

关于php - For 循环在 Laravel Controller 类中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36614952/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com