Andrew Andrew - 7 months ago 33
PHP Question

Laravel - how to save multiple rows

I have this store method:

public function store(Requests\OfferRequest $request)
{
$start = $request->input('from'); // 04/24/2016 12:00 AM
$end = $request->input('to); // 07/24/2016 12:00 AM

$auction = new Auction($request->all());
Auth::user()->auctions()->save($auction);
//how to get saved auction ID ?
}


Now I need to save empty records for each day from $start to $end in Offer table ... only I need to put id of saved auction at auction_id in offers table...

Can I save this in one query or I need to use for loop ? What is the best way ?

Answer

Use this way instead:

//how to get saved auction ID ?
$auction = new Auction();
$auction->fill($request->all());
$auction->user_id = \Auth::user()->id;
$auction->save();
$auction_id = $auction->id;

$dStart = new DateTime($start);
$dEnd   = new DateTime($to);

// Will loop through everyday from $dStart to $dEnd
while ($dStart < $dEnd) {        
    // current date of the loop formated for db use
    $date = $dStart->format('Y-m-d');

    // Code to insert date to Offer 


    $dStart->add(new DateInterval("P1D"));
}
Comments