I have some attributes, that I need to set automatically when using create() or save() methods.
Model:
class SampleModel extends Model
{
protected $guarded = ['id'];
public function setRandomColumnAttribute($value=null)
{
if(!is_string($hostname)){
$value = "I set the value here";
}
$this->attributes['random_column'] = $value;
}
}
Controller
use App\SampleModel;
class SomeController extends Controller
{
public function something()
{
SampleModel::create([
'name' => 'Jeff',
]);
// or instead of the above:
// $model = new SampleModel;
// $model->name = 'Jeff';
// $model->save();
}
}
I need to save random_column value, that is defined in the Model itself as you see, without passing it from the controller.
Please note if I use:
SampleModel::create([
'name' => 'Jeff',
'random_column' => true // or anything other than string
]);
It works and set the value, but is there any way to avoid passing this every time and just set it automatically in the Model?