1

I have the the following Post model.

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    protected $fillable = [
        'app_id',
        'title',
        'content'
  ];

    private $app_id;

    public function __construct()
    {
        $this->app_id = 43;
    }

}

I am trying to save a new post with the following code:

  $post = new Post();
  $post->title="Test title";
  $post->content="Test content";
  $post->save();

This gets saved, however the app_id isn't getting saved. Any ideas why it doesn't simply get set when I new up the object?

3 Answers 3

3

You shouldn't define private $app_id;. If you do that, Laravel's magic methods will not work when you try to set the value on the 'app_id' attribute.

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

Comments

1

Try this

$this->attributes['app_id'] = 43;

1 Comment

Thanks Niketan Raval that has fixed it, however not sure why what I had doesn't work.
1

You can do this also:

$model->setAttribute('price', 500);

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.