Maybe I'm doing things wrong, but I'm coming from the world of PDO and I'm used to be able to pass arguments to a class that a row is instantiated into and then that constructor will set a field dynamically for me. How is this achieved with Eloquent?
// Old way
$dm = new DataModel('value');
DataModel.php
class DataModel() {
function __construct($value = null) {
$this->value = $value;
}
}
I've read that Eloquent provides you with a ::create()
method but I don't want to save the record at this stage.
The issue here is that Eloquent has its own constructor and I'm not sure my model can override that constructor completely.
You can add to your model:
public function __construct($value = null, array $attributes = array())
{
$this->value = $value;
parent::__construct($attributes);
}
this will do what you want and launch parent constructor.
I believe you are looking for a thing Laravel calls Mass Assignment
You simply define an array of fillable properties, which you are then able to pass in, when creating a new object. No need to override the constructor!
class DataModel extends Eloquent {
protected $fillable = array('value');
}
$dataModel = new DataModel(array(
'value' => 'test'
));
For more Information take a look at the official docs
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With