Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

sanch012's avatar

Save row for every date in date range to DB table from one from

Hi,

I have a date and end_date input in a form. If the end date is greater than the date I would like the form to save 1 row for every date in the range between date and end_date.

I am not sure where to start with this but here is my code if someone could help.

Controller

public function store(Request $request)
    {
        $this->validate(request(), [

            'paddock' => 'required',
            'date' => 'required',
            'mob' => 'required',
            





        ]);


        $rotation = \App\Rotation::create([


            'date' => request('date'),

            'paddock' => request('paddock'),

            'divide' => request('divide'),

            'grazing' => request('grazing'),

            'mob' => request('mob'),

            'end_date' => request('end_date'),

            'team_id' => $request->user()->currentTeam->id





        ]);

        $rotation->mob = $request->get('mob');

        return redirect('/rotations/' . $rotation->mob);
    }
0 likes
2 replies
burlresearch's avatar
Level 40

If I understand what you want - you can iterate over Carbon dates quite easily:

/**
 * I have a date and end_date input in a form.
 * If the end date is greater than the date I would like the form to
 * save 1 row for every date in the range between date and end_date.
 */
public function store(Request $request)
{
    $this->validate(request(), [
        'paddock'  => 'required',
        'mob'      => 'required',
        'date'     => 'required|date',
        'end_date' => 'date',
    ]);

    $s = Carbon::parse($request->date);
    $e = Carbon::parse($request->end_date);

    for ($i = $s->copy(); $i < $e; $i->addDay()) {  // If the end_date is greater than the date
        $rotation = \App\Rotation::create([         // save 1 row for every date in the range
            'date'     => $i,
            'paddock'  => request('paddock'),
            'divide'   => request('divide'),
            'grazing'  => request('grazing'),
            'mob'      => request('mob'),
            'end_date' => request('end_date'),
            'team_id'  => $request->user()->currentTeam->id,
        ]);
    }

    return redirect('/rotations/' . $request->get('mob'));
}
1 like

Please or to participate in this conversation.