Using the Logged In User's ID to Create a Booking

Now that we have done the hard work of making a relationship both at database and Object level between the Users and Member tables the next step is relatively straightforward.

Open the file resources/views/booking/fields.blade.php. Find the code we added previously which created a dropdown list of members - as follows

We can now remove this entire label and field as we no longer need the user to select a memberid from the list of members. We can replace it with the following single line of HTML, which creates a hidden field on the form with the same name "memberid". The value in this hidden field will be pulled in from the users login using a blade helper.

<input type="hidden" name="memberid" value="{{Auth::user()->member->id}}">

Note how we "walk the object tree" calling the member( ) function on the user object which retrieves the member object associated with that user. This is equivalent to doing a SQL join to retrieve the member which is associated with that user id by the Primary Key/Foreign Key relationship.

As this new input tag is hidden, it does not need any special styling, or css so it does not have to be enclosed in any particular div tags. So we replace the entire div block highlighted above with this new single line of HTML.

Now visit http://localhost:8000/bookings/create to create a new booking. Notice how there is no longer a memberid dropdown on the form

Before you proceed, right click on the page an select "view page source" or whatever the appropriate command for your browser which will allow you to view the raw HTML behind the page. Notice the hidden field with the value already supplied.

Go ahead and submit your form to create the booking. Don't forget you have to be logged in as Morgan Bartlett! You should have now created a booking for the logged in user. Job done.

Leave a Reply