For Loop Not Working in a Laravel Controller Class

16,954

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:

$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"
Share:
16,954
avijit
Author by

avijit

I love to read books , specially biography and history . I love to program , and get adopted to new challenges such as laguage, technology , tools, algorithm .

Updated on June 05, 2022

Comments

  • avijit
    avijit almost 2 years

    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.

    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'));
        }
    }