Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing an attribute to Eloquent model constructor

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.

like image 707
silkfire Avatar asked Oct 25 '14 07:10

silkfire


2 Answers

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.

like image 162
Marcin Nabiałek Avatar answered Oct 16 '22 22:10

Marcin Nabiałek


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

like image 32
lukasgeiter Avatar answered Oct 16 '22 22:10

lukasgeiter