Passing an attribute to an Eloquent model constructor

Maybe I'm doing something wrong, but I'm coming from the PDO world, and I'm used to passing arguments to the class where the string is instantiated, and then this constructor will dynamically set the field 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 read that Eloquent provides you with the ::create() method, but I do not want to save the record at this point.

The problem here is that Eloquent has its own constructor, and I'm not sure if my model will completely override this constructor.

+5
source share
3 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 run the parent constructor.

+9
source

I believe you are looking for the thing that Laravel calls mass assignment

You simply define an array of properties to populate, which you can then pass when creating a new object. No need to redefine the constructor!

 class DataModel extends Eloquent { protected $fillable = array('value'); } $dataModel = new DataModel(array( 'value' => 'test' )); 

For more information see official docs

+4
source

old constructor format:

  protected $value; public function __construct( $value = null) { $this->value = $value; } 

new format:

 protected $value; public function __construct(array $attributes = array(), $value =null) { /* override your model constructor */ parent::__construct($attributes); $this->value = $value; } 
0
source

Source: https://habr.com/ru/post/1205486/


All Articles