Skip to content
Advertisement

Attempt to read property id on bool in Laravel

i tried assigning a value to a variable in an if condition

 if ($hotel = Hotel::whereCode($this->hotelCode)->first() && $room = Room::whereRoomCode($value)->first()) {
           if ($hotel->room_id == $room->id) {
                return true;
            }
}

I get this error

Attempt to read property “room_id” on bool

meanwhile $hotel variable is not a boolean

Advertisement

Answer

Your code can be processed by the compiler as

if ( $hotel = (
    Hotel::whereCode($this->hotelCode)->first() && $room = Room::whereRoomCode($value)->first()
    )
) {
//...
}

in that case you can see $hotel is a bool result from the && operator.

You should add parenthesis to counter the issue

if (
    ($hotel = Hotel::whereCode($this->hotelCode)->first()) &&
    ($room = Room::whereRoomCode($value)->first())
) {
    if ($hotel->room_id == $room->id) {
        return true;
    }
}

or in a more clear way

$hotel = Hotel::whereCode($this->hotelCode)->first();
$room = Room::whereRoomCode($value)->first();

return $hotel && $room && ($hotel->room_id == $room->id);

Or using relation and using way less performance (using only a count query)

public function hasRoomByRoomCode($value)
{
    return $this->room()->whereRoomCode($value)->count();
}

//this is the relation function if you did not set it yet inside Hotel::class

public function room()
{
    return $this->belongsTo(Room::class);
}
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement