1

Model

class Flight extends Model
{
    protected $fillable = ['name'];

    public $name;
}

In the controller

Flight::create(['name' => 'test']);
$flight = new Flight();
$flight->name = 'John';   //echo $flight->name 'John' it works
$flight->save();

The mass assignment creation works, however the method ->save() stores a null value for the object. I don't understand what I'm doing wrong. Please help!

1 Answer 1

1

Well, first of all, remove the public $name; from your model, why you need that?

Second, of all both:

Flight::create(['name' => 'test']);

and

$flight = new Flight();
$flight->name = 'John';
$flight->save();

Is correct.

And, where are you getting that null?

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

6 Comments

Null is being saved into the database. I just learnt that the $flight->fill(['name' => 'john]) $flight->save(); //now it will save. Why does it not work without the fill?
@artur is right, it's b/c you defined a $name property on your model, so Eloquent skips the magic where it defines your properties on the protected $attributes array which is what is saved to the database.
@Artur you should explain that in your answer.
I see, removing the public $name allows it to work. Originally I put it to private $name as I need to access the variables later. For example $this->flightCode = $this->name.'-1DH'; Im in the habit of using getters and setters, can this still be achieved without the use of private $name;
Yes that'll still work without a declared $name property. Also, it doesn't matter if it's public or private, if there's a $name property defined at all, it'll skip the magic. Don't skip the magic!
|

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.