1

Why can't I do this:

protected $attributes = array('name' => config('app.name'));

I get the following error:

Constant expression contains invalid operations

EDIT: I should mention that the issue occurs when I do this in an Eloquent Model. If I do the following it works fine:

protected $attributes = array('name' => 'my app');
2
  • Is this the line the error is generated? And what is the result of config('app.name')? Commented Mar 22, 2017 at 14:33
  • Have edited to hopefully answer Commented Mar 22, 2017 at 14:37

2 Answers 2

1

The attributes property in Eloquent is (if I recall correctly) static (or Eloquent itself is static) and you only use constants to fill a static property (or a method).

If you add a construct to your class (in which you also call the parent construct) you can alter the attributes:

public function __construct(array $attributes = [])
{
    $this->attributes = array('name' => config('app.name'));
    parent::__construct($attributes);
}

But don't forget that Laravel itself uses the attributes property, so you should probably use another name or add it to the array instead of setting it!

Sign up to request clarification or add additional context in comments.

1 Comment

Works for me. Thanks!
0

Try it this way instead:(I hope it helps)

In your model:

private $attributes;

In a function in your model:

public function anyfunction()
    {
       $this->attributes =  array('name' => config('app.name'));

        dd($this->attributes);
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.