I want to show the user name that user has booked to slot using laravel

Viewed 22

I want to show user name that user has booked to slot on calender and i have already made relation how can i show username please help me thanks.

enter image description here

Booking Model

    public function users(){
        return $this->hasOne('App\Models\User','id','user_id');
    }

Controller

  public function getBookingSlot(Request $request){

        $userBookings = Booking::with('users')->where('room_id',$request->room_id)->where('booking_holding_status',1)->get();

        foreach($userBookings as $booking){

            $events []  = [
                'id'            => $booking->id,
                'calendarId'    => $booking->id,
                'title'         => 'user name',
                'category'      => 'time',
                'dueDateClass'  => '',
                'bgColor'       => "#e6515f",
                'color'         => "#ffffff",
                'isPending'     => 'false',
                'isFocused'     =>'false',
                'start'         => $booking->start_datetime,
                'end'           => $booking->end_datetime,
            ];

        }

            return  \Response::json([
                'events' => $events ?? null
            ]);
    }
1 Answers
$booking->users[0]->username;

booking object contains booking details in it along with the object of users which it selects from the user table... I am not sure about hasOne() relationship. I have used it with belongsToMany().

so you get the user object from the booking object than for the first user [0] get its username.

If this does not work then the booking object may have only 1 user object, not an array of objects.. then access it like this...

$booking->users->username;
Related