'Setting properties in laravel model

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?



Solution 1:[1]

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.

Solution 2:[2]

You can do this also:

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dragos
Solution 2 Mustafa Omar