Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

meanwhile $hotel variable is not a boolean

>Solution :

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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading