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.
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);
});
CodePudding user response:
You're doing a few things you don't need to here.
When you call
create()
, it persists to the Database, so calling->save()
later is redundant.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();
}