Sharing create and update form in Laravel

Viewed 21

I'm learning Laravel and have created a single form that is shared by the create and edit controller.

The create controller just returns the view.

 public function create()
    {
        return view('hotels.create');
    }

However i've had to put my edit controller and return it in an array

    return view('hotels.edit', [
       'hotel' => Hotel::with('hotelFacilities')->where('id', $id)->get()
    ]);

Now in my view I have to pass

$hotel[0]->hotelFacilities->fitness_centre

instead of

$hotel->hotelFacilities->fitness_centre

So now my create view is looking for $hotel where it is now $hotel[0] in the shared view. How can I change this so it's looking at the same reference to the $hotel variable?

1 Answers

If you are using the same view for create and edit, you have to pass the same object for views. change code as below.

return view('hotels.create', [
   'hotel' => new Hotel
]);

return view('hotels.edit', [
   'hotel' => Hotel::with('hotelFacilities')->where('id', $id)->first()
]);
Related