For 循环在 Laravel 控制器类中不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36614952/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
For Loop Not Working in a Laravel Controller Class
提问by avijit bhattacharjee
In my Laravel project, I have a BusController.php file where I need to run a for() loop. However, the loop is not working. I also tried a blade for looping but have the same problem.
在我的 Laravel 项目中,我有一个 BusController.php 文件,我需要在其中运行 for() 循环。但是,循环不起作用。我也试过一个刀片来循环,但有同样的问题。
BusController.php
总线控制器.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'));
}
}
回答by niko
Make sure you have validated the data you received from the Request
. Because if you don't the loop will be fail since the loop condition
will always be false.
And to test it, here's what I do:
确保您已验证从Request
. 因为如果你不这样做,循环就会失败,因为loop condition
永远是假的。为了测试它,这就是我所做的:
$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);
Output:
输出:
string(0) ""
And here it is working one:
在这里它正在工作:
$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);
Output:
输出:
string(40) "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"