Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if model property is set (when null)

Tags:

php

laravel

Say I have a model called Fruit which can have a null value for seeds. The seeds column exists in the database table.

The problem is that using isset is returning false for this model property when it is set to null, or maybe it has something to do with the __magic stuff in general? So how do I check if the model has the property seeds even when it is set to null or declared via magic?

For example:

$fruit = Fruit::find(1);

if (isset($fruit->seeds)) {
  echo 'Yes';
}
else {
  echo 'No';
}

This will echo No if the value of seeds is set to null in the database.

like image 779
kjdion84 Avatar asked Oct 16 '25 18:10

kjdion84


1 Answers

You can use is_null():

if (isset($fruit->seeds) && !is_null($fruit->seeds)) {
like image 67
Alexey Mezenin Avatar answered Oct 18 '25 09:10

Alexey Mezenin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!