How to set the default value of an attribute on a Laravel model
You can set Default attribute in Model also>
protected $attributes = [
'status' => self::STATUS_UNCONFIRMED,
'role_id' => self::ROLE_PUBLISHER,
];
You can find the details in these links
1.) How to set a default attribute value for a Laravel / Eloquent model?
2.) https://laracasts.com/index.php/discuss/channels/eloquent/eloquent-help-generating-attribute-values-before-creating-record
You can also Use Accessors & Mutators for this
You can find the details in the Laravel documentation
1.) https://laravel.com/docs/4.2/eloquent#accessors-and-mutators
2.) https://scotch.io/tutorials/automatically-format-laravel-database-fields-with-accessors-and-mutators
3.) Universal accessors and mutators in Laravel 4
How to set a default attribute value for a Laravel / Eloquent model?
This is what I'm doing now:
protected $defaults = array(
'quantity' => 9,
);
public function __construct(array $attributes = array())
{
$this->setRawAttributes($this->defaults, true);
parent::__construct($attributes);
}
I will suggest this as a PR so we don't need to declare this constructor at every Model, and can easily apply by simply declaring the $defaults
array in our models...
UPDATE:
As pointed by cmfolio, the actual ANSWER is quite simple:
Just override the $attributes
property! Like this:
protected $attributes = array(
'quantity' => 9,
);
The issue was discussed here.
How do you set default attribute values for a custom pivot table?
Turns out this one still hasn't been implemented.
There is a closed proposal for this: https://github.com/laravel/ideas/issues/872
Currently you can only use wherePivot()
feature which actually sets default attributes but it's main purpose is filtering, so you still can not set defaults without filtering which is pretty weird as for me.
https://github.com/laravel/framework/pull/22867
How to set default attribute values in a laravel 4 model
Accessors are what you are looking for. As the name states Accessors will be called whenever you try to access that certain property on the eloquent model.
<?php
class MyModel extends Eloquent {
public function getImageAttribute($value)
{
if(is_null($value))
return 'default_image.jpg';
return $value;
}
}
Update:
Just for clarification reasons: When you try to access attributes that do not exist on a class, PHP invokes the __get()
magic method (if it does exist), instead of complaining.
Eloquent works exactely the same way. When __call()
is invoked (remember, attributes you call on an eloquent model do not really exist) laravel will give you the value of that field from your database. The trick comes in here.
When the __get()
method is called on an eloquent model. Eloquent will call it's getAttribute()
method which grabs the attribute but checks if an accessor exists beforehand (in laravel source accessors are called get mutators). You can see it here.
If that's the case laravel calls the mutateAttribute()
method on the given key. The mutateAttribute()
will then eventually call the getXAttribute
(source) where X
is the name of the attribute being accessed.
That's the whole trick behind the magic that's going, and again shows how well structured laravels source is.
Laravel - Change default value eloquent
Almost; you can change getStatus()
to getStatusAttribute()
, which is a Laravel Accessor, then simply call:
$payment = Payment::first();
dd($payment->status);
// Or
$payments = Payment::get();
foreach($payments AS $payment){
dd($payment->status);
}
Instead of outputting 1
, 2
, etc. this will override the value to 'Waiting for payment'
, 'In review'
, etc.
See https://laravel.com/docs/6.x/eloquent-mutators#defining-an-accessor for full details.
Eloquent use default value if column is null
withDefault
works when the relationship is null, not the field values. See Null Object Pattern for more information.
You might be better served by model events, specifically creating
for when new IvendiFinanceCalculatorSetting
records are inserted.
Then in the model's boot
method or an observer class, you can set default setting values:
// IvendiFinanceCalculatorSettingObserver.php example
public function creating (IvendiFinanceCalculatorSetting $setting) {
$setting->setAttribute('column1', 'Default');
$setting->setAttribute('column2', 0);
}
Another approach is setting the default values directly in the model's attribute property:
/**
* The model's default values for attributes.
*
* @var array
*/
protected $attributes = [
'column1' => 'Default',
'column2' => 0
];
Related Topics
How to Get Time Zone Through Ip Address in PHP
What Security Issues Should I Look Out for in PHP
How to Pass Arguments to My Function Through Add_Action
How to Use Class Methods as Callbacks
Sqlstate[Hy000] [1698] Access Denied for User 'Root'@'Localhost'
How to Build Unlimited Level of Menu Through PHP and MySQL
PHP Regular Expression for Strong Password Validation
PHP Include Best Practices Question
How to Run a PHP Without a Web Server
Manipulate a Url String by Adding Get Parameters
Wamp/MySQL Errors Not in Correct Language
How to Preview an Image Before and After Upload
Routing Controllers in Subfolders Using Codeigniter