jon
jon

Reputation: 1591

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?

Upvotes: 1

Views: 6598

Answers (3)

Mustafa Omar
Mustafa Omar

Reputation: 449

You can do this also:

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

Upvotes: 1

Dragos
Dragos

Reputation: 85

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.

Upvotes: 3

Niketan Raval
Niketan Raval

Reputation: 479

Try this

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

Upvotes: 1

Related Questions