this-laravel-casting-error-made-me-pull-my-hair-out

This Laravel casting error made me pull my hair out

I was working on a project in Laravel and I came into a error while casting a boolean variable. Although the problem was a small one, but sometimes the smallest problems takes the longest to solve. My project was a platform that allows patients to connect with their doctors. It has a feature where I show patients their favourite doctors. A patient mark a doctor his favourite and he will be start displaying in my favourite list.

The problem arises when I tried to cast a variable “is_favourite” to boolean. I was using MySQL database and in MySQL you cannot directly use “true” or “false”, instead you have to use 0 or 1 for false and true respectively. So my goal was to fetch the data from database and when I cast it to boolean, it will automatically convert it to true or false. I was able to fetch the data correctly, but when try to cast it, it returns an error “Undefined property: $is_favourite“.

$obj = [
    "is_favourite" => (bool) $c->is_favourite ?? false
];

Even when I try to dd($c), I can see the $is_favourite variable.

The solution was simple.

Solution 1

I can use a Laravel helper function “data_get” to safely get the value from $c object:

$obj = [
    "is_favourite" => (bool) data_get($c, "is_favourite", false)
];

“data_get” is a Laravel built-in helper function. It accepts 3 arguments:

  1. First argument is the object or an array whos property you want to access.
  2. Second is the key or property name.
  3. Third argument is the default value.

Finally, we are casting this to boolean and thus my error resolved.

Solution 2

The solution 1 was Laravel specific. But PHP has many frameworks and a lot of developers. Some are working in native PHP as well. So I need to find a solution that works in native PHP. Because if it can work in native PHP, then it can work in all PHP frameworks as well.

I can wrap the null coalescing operator (??) in parenthesis:

$obj = [
    "is_favourite" => (bool) ($c->is_favourite ?? false)
];

The error was due to operator precedence. When I was casting it to boolean (without wrapping in parenthesis), the null coalescing operator (??) was not being run at all. I need to run the null coalescing operator (??) first, with default value. Then cast the value to boolean.

That’s how I solve this casting error in my Laravel project. I thought to share it with others so if someone else got into this problem, he will find a solution here.