pickab00
174
11
Laravel

Edit hasMany relationship

Posted 1 month ago by pickab00

I have a reservation and guestpax table. Both of the models relationships looks like this,

//GuestPax Model
class GuestPax extends Model
    {
            public function reservation(){
            return $this->belongsTo('App\Reservation');
        }
}


//Reservation Model
class Reservation extends Model
    {
            public function guestpaxes(){
            return $this->hasMany('App\GuestPax');
        }
}

Reservation model hasMany guest paxes and GuestPax belongsTo each Reservation.

I am using this to add the paxes,

HTML:

<input type="text" name="pax_name[]" class="btn btn-grey m-r-5 m-b-5" readonly  value="test">
<input type="text" name="pax_name[]" class="btn btn-grey m-r-5 m-b-5" readonly  value="test1">
<input type="text" name="pax_name[]" class="btn btn-grey m-r-5 m-b-5" readonly  value="test2">

Controller:

$paxNames = $request->pax_name;

if ($request->has('pax_name')) {
        foreach ($paxNames as $paxInsert) {

            $pax = new GuestPax;

    //This $insert->id comes from the code which saves reservation detail. that code comes before this foreach. its like $insert->save; with a bunch of other data. So I am just taking that newly created reservations ID
            $pax->reservation_id = $insert->id;

            $pax->name = $paxInsert;

            $pax->save();
        }
    }

So assuming that now I am on edit, how can I edit the existing data? The only change I made was to rename the name of the edit input fields to name="existing_pax_name[]" so I can differentiate the existing and newly added. I am using JQuery to add input/append these input fields.

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.