Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

raihanrazon's avatar

Laravel 11 Model custom attribute returns null

I have added a custom attribute 'lorem' in my Setting Model. This doesn't exist in my DB table.

class Setting{

  ...
  public function lorem(): Attribute
    {
      return new Attribute(
        get: fn () => "ipsum",
      );  
    }
  }
}    			

Following shows that 'lorem' is included in the array dump.

$setting = Setting::find(1)->append('lorem');
dd($setting ->toArray() );

array:16 [
  ...
  "lorem" => "ipsum"
] 

However, when I try to access the attribute from the object it gives me null

dd($element->lorem); // returns null

How do I get the desired value directly using the above line?

Thanks

0 likes
2 replies
LaryAI's avatar
LaryAI
AI
Best Answer
Level 58

The issue you're encountering is likely due to the way you're trying to access the custom attribute. When you use the append method, it adds the attribute to the array representation of the model, but it doesn't make it directly accessible as a property of the model instance.

To access the custom attribute directly, you should ensure that the attribute is defined as an accessor in your model. Here's how you can modify your Setting model to achieve this:

use Illuminate\Database\Eloquent\Casts\Attribute;

class Setting extends Model
{
    // Other model methods and properties

    protected function lorem(): Attribute
    {
        return new Attribute(
            get: fn () => "ipsum",
        );
    }
}

With this setup, you should be able to access the lorem attribute directly from the model instance:

$setting = Setting::find(1);
dd($setting->lorem); // This should now return "ipsum"

Make sure that your Setting model extends Illuminate\Database\Eloquent\Model and that you have imported the Attribute class correctly. This should resolve the issue and allow you to access the custom attribute directly.

Please or to participate in this conversation.