I have a Laravel model which has various fields that default to NULL in the database and cannot easily be changed for legacy reasons. I would like to always return these as an empty string, for example, when returning JSON back from my route. Is there a "standard" way to define defaults in a model somehow?
Another case might be that a certain field always needs some processing done on it before being returned, can this also be defined in a similar way? Thanks.
The various approaches to solving the Set Default Value For Column In Laravel Model problem are summarised in the following code. You can use change() method: Schema::table('users', function ($table) { $table->integer('active')->default(0)->change(); });
Foreign Keys Laravel also provides support for adding foreign key constraints to your tables: $table->integer('user_id')->unsigned(); $table->foreign('user_id')->references('id')->on('users'); In this example, we are stating that the user_id column references the id column on the users table.
The fillable property is used inside the model. It takes care of defining which fields are to be considered when the user will insert or update data. Only the fields marked as fillable are used in the mass assignment. This is done to avoid mass assignment data attacks when the user sends data from the HTTP request.
Eloquent is an object relational mapper (ORM) that is included by default within the Laravel framework. An ORM is software that facilitates handling database records by representing data as objects, working as a layer of abstraction on top of the database engine used to store an application's data.
You can specify default values with the $attributes
property:
class MyModel extends Eloquent {
protected $attributes = array(
'foo' => 'bar'
);
}
However I think this will still be overwritten by the NULL
from the db. The use case for $attributes
is rather when creating and inserting new records.
To change your model before it is converted to JSON / into an array you can override toArray()
in your model:
public function toArray(){
$array = parent::toArray();
foreach($array as &$value){
if($value == null){
$value = '';
}
}
return $array;
}
If you have certain fields that require special kind of processing (e.g. formatting a date, concatenating two attributes) you can use an accessor:
public function getFullNameAttribute(){
return $this->attributes['firstname'].' '.$this->attributes['lastname'];
}
Now you can access it by $model->full_name
(or $model->fullName
whichever you prefer)
And finally, to add it to the JSON / array output, use $appends
protected $appends = array('full_name');
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