Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Saving one to one in Laravel

I’m just learning some Laravel 9 and i’m doing a simple one to one relationship on two tables. I’ve created the relationships and the foreign keys which are working fine.

I am trying to create a new Hotel which saves info into the Hotels model and the facilities into the facilities model and are joined by the hotel_id as the foreign key.

I can’t quite get my transaction right, where I have the hotel but need to pick up the id for it to pass and also have it as my foreign key on the facilities table.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 DB::transaction(function () use ($request) {
        $hotel = Hotel::create([
            'name' => $request->input('name'),
            'address' => $request->input('address'),
            'postcode' => $request->input('postcode'),
            'state' => $request->input('state'),
            'star_rating' => $request->input('star_rating'),
        ]);

        $facility = HotelFacility::create([
            'hotel_id' => 39,
            'fitness_centre' => true,
            'bar' => false,
            'bar' => true,
            'parking' => true,
            'free_wifi' => true,
        ]);
        Hotel::find($hotel->id)->facility()->save($facility);
    });

>Solution :

You’re doing a few things you don’t need to here.

  1. When you call create(), it persists to the Database, so calling ->save() later is redundant.

  2. The last line is completely unnecessary as well.

There’s ways to do this code by using relationship methods:

DB::beginTransaction();
try {
  $hotel = Hotel::create([
    'name' => $request->input('name'),
    'address' => $request->input('address'),
    'postcode' => $request->input('postcode'),
    'state' => $request->input('state'),
    'star_rating' => $request->input('star_rating'),
  ]);

  $hotel->facility()->create([
    'fitness_centre' => true,
    'bar' => false,
    'parking' => true,
    'free_wifi' => true,
  ]);

  DB::commit();
} catch (Exception $ex) {
  DB::rollBack();
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading